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

如何用PHP判断单词是否独立存在而非子串?附示例

PHP 实现独立单词的存在性检查与计数

要判断一个单词是否作为独立单词存在于字符串中(而非其他单词的子串),可以利用正则表达式的**单词边界(\b)**特性来实现,这能精准区分独立单词和子串。以下是具体的代码示例:

检查单词是否存在

这个函数会返回布尔值,告知目标单词是否以独立形式出现在字符串中:

function isWordPresent(string $string, string $word, bool $caseInsensitive = true): bool {
    // 转义目标单词中的正则特殊字符,避免解析错误
    $escapedWord = preg_quote($word, '/');
    // 决定是否启用大小写不敏感匹配
    $modifier = $caseInsensitive ? 'i' : '';
    // 构建包含单词边界的正则模式
    $pattern = "/\b$escapedWord\b$modifier";
    
    return preg_match($pattern, $string) === 1;
}

// 测试示例
$sentence = "As I look at the photo the boy looks photogenic";
$targetWord = 'photo';

var_dump(isWordPresent($sentence, $targetWord)); // 输出 bool(true)
var_dump(isWordPresent($sentence, 'phot')); // 输出 bool(false),因为"phot"只是"photogenic"的子串

统计独立单词的出现次数

如果需要统计目标单词作为独立单词出现的次数,可以使用preg_match_all:

function countWordOccurrences(string $string, string $word, bool $caseInsensitive = true): int {
    $escapedWord = preg_quote($word, '/');
    $modifier = $caseInsensitive ? 'i' : '';
    $pattern = "/\b$escapedWord\b$modifier";
    
    preg_match_all($pattern, $string, $matches);
    return count($matches[0]);
}

// 测试示例
$sentence = "As I look at the photo the boy looks photogenic, Photo is my favorite!";
$targetWord = 'photo';

echo countWordOccurrences($sentence, $targetWord); // 输出 2(大小写不敏感匹配)
echo countWordOccurrences($sentence, $targetWord, false); // 输出 1(仅匹配小写的"photo")

关键说明

  • preg_quote的作用:必须用它转义目标单词中的正则特殊字符(如.、*、?等),否则这些字符会被当作正则语法处理,导致匹配结果错误。
  • 单词边界\b:它匹配的是"单词字符(字母、数字、下划线)"与"非单词字符"之间的位置,或者字符串的开头/结尾。这就确保了我们匹配的是完整的独立单词,而非像"photo"在"photogenic"中的子串部分。
  • 大小写控制:通过$caseInsensitive参数可以灵活切换是否区分大小写,默认开启不敏感匹配。

内容的提问来源于stack exchange,提问作者Rendell Eyas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:30:24