如何使用PHP检查一个单词是否包含在另一个字符串中?

2022-08-30 09:02:57

伪代码

text = "I go to school";
word = "to"
if ( word.exist(text) ) {
    return true ;
else {
    return false ;
}

我正在寻找一个PHP函数,如果文本中存在该单词,则返回true。


答案 1

根据您的需要,您有几种选择。对于这个简单的示例,可能是最简单,最直接的函数。如果需要对结果执行某些操作,则可能首选 或 。如果您需要使用复杂的图案而不是绳子作为针,则需要。strpos()strstr()preg_match()preg_match()

$needle = "to";
$haystack = "I go to school";

strpos() 和 stripos() 方法 (stripos() 不区分大小写):

if (strpos($haystack, $needle) !== false) echo "Found!";

strstr() 和 stristr() 方法(stristr 不区分大小写):

if (strstr($haystack, $needle)) echo "Found!";

preg_match方法(正则表达式,更灵活,但运行速度较慢):

if (preg_match("/to/", $haystack)) echo "Found!";

因为你要求一个完整的函数,所以这就是你把它放在一起的方式(使用针和大海捞针的默认值):

function match_my_string($needle = 'to', $haystack = 'I go to school') {
  if (strpos($haystack, $needle) !== false) return true;
  else return false;
}

PHP 8.0.0 现在包含一个str_contains函数,其工作原理如下:

if (str_contains($haystack, $needle)) {
    echo "Found";
}

答案 2
function hasWord($word, $txt) {
    $patt = "/(?:^|[^a-zA-Z])" . preg_quote($word, '/') . "(?:$|[^a-zA-Z])/i";
    return preg_match($patt, $txt);
}

如果$word是“to”,这将匹配:

  • “听我说”
  • 《去月球》
  • “最新”

但不是:

  • “在一起”
  • “进入太空”

推荐