如何检查一个字是否包含在使用PHP的另一个string中?
伪代码
text = "I go to school"; word = "to" if ( word.exist(text) ) { return true ; else { return false ; } 我正在寻找一个PHP函数,如果文本中存在该单词,则返回true。
 你有几个select取决于你的需求。 对于这个简单的例子, strpos()可能是最简单和最直接的函数。 如果你需要对结果做些什么,你可能更喜欢strstr()或者preg_match() 。 如果你需要使用一个复杂的模式,而不是一个string作为你的针,你会想要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方法 (正则expression式,更灵活,但运行速度更慢):
 if (preg_match("/to/", $haystack)) echo "Found!"; 
因为你要求一个完整的function,这就是你如何把它放在一起(用针和干草堆的默认值):
 function match_my_string($needle = 'to', $haystack = 'I go to school') { if (strpos($haystack, $needle) !== false) return true; else return false; } 
使用:
 return (strpos($text,$word) !== false); //case-sensitive 
要么
 return (stripos($text,$word) !== false); //case-insensitive 
 function hasWord($word, $txt) { $patt = "/(?:^|[^a-zA-Z])" . preg_quote($word, '/') . "(?:$|[^a-zA-Z])/i"; return preg_match($patt, $txt); } 
如果$ word是“to”,这将匹配:
- “听我说”
- “到月球”
- “上到了分钟”
但不是:
- “一起”
- “进入太空”
strpos
 <?php $text = "I go to school"; $word = "to" $pos = strpos($text, $word); if ($pos === false) { return false; } else { return true; } ?> 
 $text="I go to school"; return (strpos($text, 'to')!== false); 
你需要find正确使用strpos的手册页
另一种方法(除了已经给出的strpos示例之外,还使用'strstr'函数:
 if (strstr($haystack, $needle)) { return true; } else { return false; } 
你可以使用这些string函数,
strstr – 查找第一个出现的string
stristr – 不区分大小写的strstr()
strrchr – 查找string中最后一次出现的字符
strpos – 查找string中第一次出现子string的位置
strpbrk – 在string中search任何一组字符
 如果这没有帮助,那么你应该使用preg正则expression式 
preg_match – 执行正则expression式匹配
@mrclay
不能,我们只是做
 "/(?:^|\w+)" . preg_quote($word, '/') . "(?:$|\w+)/i" 
所以它要么检查开始或空白,结束或空白。
经过多次searchfind合适的php版本,我决定编写自己的包含函数(带有多个参数针)并记住。
 function contains($str,$contain) { if(stripos($contain,"|") !== false) { $s = preg_split('/[|]+/i',$contain); $len = sizeof($s); for($i=0;$i < $len;$i++) { if(stripos($str,$s[$i]) !== false) { return(true); } } } if(stripos($str,$contain) !== false) { return(true); } return(false); } 
php的描述包含:
 contains($str,$arg) $str: The string to be searched $arg: The needle, more arguments divided by '|' 
例子:
 $str = 'green house'; if(contains($str,"green")) echo "we have a green house."; else echo "our house isn't green"; $str = 'green, blue, red houses'; if(contains($str,"green|red")) echo "we have a green or red house."; else echo "we have a blue house."; 
 在php中使用strpos函数。 
 $text = "I go to school"; $word = "to" if (strpos($text,$word)) { echo 'true'; }