我的第一个问题,所以请对我有耐心.
我有一根绳子:
“创建一个脚本,它将需要一个字符串并进行分析以产生以下统计数据。辛辣的墨西哥腊肉和凯文水牛法兰克福香肠,香肠干猪肉肚皮培根。Doner香肠,alcatra短腰肉,鸡腿火腿,嫩肉火腿,bresaola porchetta肉丸酱,里贝耶猪肉腰果,比得上猪肋,舌尖鸡肋,舌尖鸡腿,圆猪排,基贝拉培根,牛排和火腿,短排骨,鹿肉,肉排,牛排。”
我使用了这个功能:
$sentenceArray = preg_split('/[.]+/', $string);
foreach ($sentenceArray as $sentence) {
$numberOfWords = str_word_count($sentence);
echo '<br>' . $numberOfWords . '<br>';
}我明白了:
16
14
16
18
17
0我期待16,14,16,18,17,但我不明白0是从哪里来的?!非常感谢!
发布于 2021-05-24 09:45:05
这是因为您的输入字符串以一个点结束,而preg_split也将在那个点拆分,生成后面的字符串作为分隔符,即空字符串。
使用preg_match_all代替。这个函数将结果数组作为参数,而不是作为返回值,并且该数组将被包装。也是如此:
preg_match_all('/[^.]+/', $string, $sentenceArray);
foreach ($sentenceArray[0] as $sentence) {
$numberOfWords = str_word_count($sentence);
echo '<br>' . $numberOfWords . '<br>';
}发布于 2021-05-24 09:53:07
preg_split()在句柄上分裂,包括最后一个句点,这会导致数组中返回一个空字符串。
有一个标志可以用来删除空元素。
$sentenceArray = preg_split('/[.]+/', $string, -1, PREG_SPLIT_NO_EMPTY);有关更多细节,请参见https://www.php.net/manual/en/function.preg-split.php
发布于 2021-05-24 09:45:00
实际上,您需要排除不包含任何内容的最后一个字符串,这就是为什么它要返回其中的0个单词。您可以使用以下代码。
<?php
$string = "Create a script which will take a string and analyse it to produce the following stats. Spicy jalapeno bacon ipsum dolor amet kevin buffalo frankfurter, sausage jerky pork belly bacon. Doner sausage alcatra short loin, drumstick ham tenderloin shank bresaola porchetta meatball jowl ribeye ground round. Ribeye pork loin filet mignon, biltong shoulder short ribs tongue ball tip drumstick ground round rump pork chop. Kielbasa bacon strip steak andouille ham short ribs short loin venison frankfurter spare ribs doner corned beef.";
$sentenceArray = explode(".", $string);
foreach ($sentenceArray as $sentence)
{
if ($sentence != "")
{
$numberOfWords = str_word_count($sentence);
echo '<br>' . trim($numberOfWords) . '<br>';
}
}
?>https://stackoverflow.com/questions/67669785
复制相似问题