You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:05:22