逗号分隔句子php的第一个单词

时间:2017-09-20 10:02:46

标签: php

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

我想输出" Hi Name"。

[基本上以逗号分隔的句子的第一个字]。

然而,有时我的句子也可以是我的,"名字是,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){}
    }

2 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:0)

基本上使用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;
}

它将输出Hi Name两次

Demo