伪代码
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)
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)
<?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)