如何用PHP循环提取句子前两个单词?现有代码故障求助
问题分析与修复方案
原代码存在的错误
- 错误使用
str_word_count($words)判断单词数量:str_word_count的参数应为字符串,而$words是数组,需改用count($words)获取数组元素个数。 - 逻辑完全不符合需求:需求是保留完整单词,原代码却用
mb_substr($w, 0, 1)提取每个单词的首字母,无论单/多单词场景都偏离要求。 - 潜在隐患:
explode(' ', $inp_val)分割字符串时,若存在连续空格或首尾空格,会生成空数组元素,导致单词数量判断错误。
修复后的代码
基础版本(适用于输入无连续空格的场景)
$inp_val = "this is our country"; $words = explode(' ', $inp_val); $shop_name = ""; if (count($words) == 1) { $shop_name = $words[0]; } else { $shop_name = $words[0] . ' ' . $words[1]; } echo $shop_name; // 输出:this is
健壮版本(处理连续空格、首尾空格等异常输入)
$inp_val = " this is our country "; // 用正则分割任意数量空白字符,同时过滤空元素 $words = preg_split('/\s+/', trim($inp_val), -1, PREG_SPLIT_NO_EMPTY); $shop_name = ""; $wordCount = count($words); if ($wordCount == 0) { $shop_name = ""; // 处理空输入 } elseif ($wordCount == 1) { $shop_name = $words[0]; } else { $shop_name = $words[0] . ' ' . $words[1]; } echo $shop_name; // 输出:this is
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

