如何正确地获取每个句子的第一个单词并通过php将值推入数组

mzsu5hc0  于 2023-08-02  发布在  PHP
关注(0)|答案(2)|浏览(125)

这个脚本通过获取句子中每个第一个单词的值来工作得很好,例如(Ann和Mike)。我的问题是数组的输出不是我想要的。
我期待着$result_names = array("Ann","Mike");,但我得到了

Array ( [0] => Ann [1] => Ann Mike )

字符串

这里是代码

$names = array();

$str = 'Ann is good,"Mike loves cooking"';
$result = explode(',',$str); //parsing with , as delimiter 
$op = "";
foreach($result as $value)
{
    $tmp = explode(' ',$value);
    $op .= trim($tmp[0],"'\"")." ";

 $names[] = $op;

}
$op = rtrim($op);
$rr = ucwords($op);

print_r($names);

nwsw7zdq

nwsw7zdq1#

您的代码连接您的值:

$op .= trim($tmp[0],"'\"")." ";

字符串
试着用一个作业来代替这个

$op = trim($tmp[0],"'\"")." ";


Documentation

7vux5j2d

7vux5j2d2#

$str = 'Ann is good,"Mike loves cooking"';
$sentences = str_replace(["'", '"'], '', explode(',', $str));

$names = array_map(
    fn($s) => explode(' ', trim($s))[0],
    $sentences
);

print_r($names);

字符串

相关问题