Php 逗号分隔句的第一个单词

Php 逗号分隔句的第一个单词,php,Php,我的字符串是:嗨,我的名字是abc 我想输出“Hi Name” [基本上是逗号分隔句的第一个单词] 然而,有时我的句子也可以是Hi my,“name is,abc” [如果句子本身有逗号,则该句子用“.”括起来 在这种情况下,我的输出也应该是“Hi Name” 到目前为止,我已经做到了 $str = "hi my,name is abc"; $result = explode(',',$str); //parsing with , as delimiter foreach ($result a

我的字符串是:嗨,我的名字是abc

我想输出“Hi Name”

[基本上是逗号分隔句的第一个单词]

然而,有时我的句子也可以是Hi my,“name is,abc”

[如果句子本身有逗号,则该句子用“.”括起来

在这种情况下,我的输出也应该是“Hi Name”

到目前为止,我已经做到了

$str = "hi my,name is abc";
$result = explode(',',$str); //parsing with , as delimiter 
foreach ($result as $results) {
    $x = explode(' ',$results); // parsing with " " as delimiter 
        forach($x as $y){}
    }

您可以使用
explode
获得结果,对于IGINORE
使用trim

$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter 
$first = explode(' ',$result[0]);
$first = $first[0];

$second = explode(' ',$result[1]);
$second = trim($second[0],"'\"");
$op = $first." ".$second;
echo ucwords($op);
编辑或者,如果希望对所有对象都使用它,则分隔的值使用foreach

$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter 
$op = "";
foreach($result as $value)
{
    $tmp = explode(' ',$value);
    $op .= trim($tmp[0],"'\"")." ";
}
$op = rtrim($op);
echo ucwords($op);

使用explode、str_pos等基本上很难解决这个问题。在这种情况下,您应该使用状态机方法

<?php
function getFirstWords($str)
{
    $state = '';
    $parts = [];
    $buf = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $char = $str[$i];

        if ($char == '"') {
            $state = $state == '' ? '"' : '';
             continue;
         }

         if ($state == '' && $char == ',') {
             $_ = explode(' ', trim($buf));
             $parts[] = ucfirst(reset($_));
             $buf = '';
             continue;
         }
         $buf .= $char;
    }
    if ($buf != '') {
        $_ = explode(' ', trim($buf));
        $parts[] = ucfirst(reset($_));
    }

    return implode(' ', $parts);
}


foreach (['Hi my, "name is, abc"', 'Hi my, name is abc'] as $str) {
     echo getFirstWords($str), PHP_EOL;
}

“name is”将出现在所有输入中??是否像“name is xxxx”“?@BSB编号。。这根绳子只是一根绳子example@Ank试试这个,我假设您在声明中有一个
,为什么我有DownVoteWorks。。但我在结尾有尾随空格。对于第二个解决方案,请尝试编辑答案。添加了
rtime
以删除右侧的空间