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

Was*_*eem 61 php string

伪代码

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

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

pix*_*x0r 106

根据您的需要,您有几个选择.对于这个简单的例子,strpos()可能是最简单和最直接的函数.如果你需要对结果做些什么,你可能更喜欢strstr()preg_match().如果您需要使用复杂的图案而不是字符串作为针,您需要preg_match().

$needle = "to";
$haystack = "I go to school";
Run Code Online (Sandbox Code Playgroud)

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

if (strpos($haystack, $needle) !== false) echo "Found!";
Run Code Online (Sandbox Code Playgroud)

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

if (strstr($haystack, $needle)) echo "Found!";
Run Code Online (Sandbox Code Playgroud)

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

if (preg_match("/to/", $haystack)) echo "Found!";
Run Code Online (Sandbox Code Playgroud)

因为你要求一个完整的功能,所以你可以将它们放在一起(使用needle和haystack的默认值):

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

  • 非phperers(像我一样)注意`!== false`中的双等号,因为如果在字符串的开头找到匹配(字符位置为零),strpos()可能返回0. (3认同)
  • 难道你不能只做`return(strpos($ haystack,$ needle)!== false);`?它具有完全相同的结果,只是一个更干净的代码 (3认同)

Ste*_*lay 15

function hasWord($word, $txt) {
    $patt = "/(?:^|[^a-zA-Z])" . preg_quote($word, '/') . "(?:$|[^a-zA-Z])/i";
    return preg_match($patt, $txt);
}
Run Code Online (Sandbox Code Playgroud)

如果$ word是"to",则匹配:

  • "听我说"
  • "到月球"
  • "上到了分钟"

但不是:

  • "一起"
  • "进入太空"


Jon*_*and 13

使用:

return (strpos($text,$word) !== false); //case-sensitive
Run Code Online (Sandbox Code Playgroud)

要么

return (stripos($text,$word) !== false); //case-insensitive
Run Code Online (Sandbox Code Playgroud)


jit*_*ter 5

strpos

<?php
$text = "I go to school";
$word = "to"
$pos = strpos($text, $word);

if ($pos === false) {
    return false;
} else {
    return true;
}
?>
Run Code Online (Sandbox Code Playgroud)