测试字符串是否包含 PHP 中的单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9119101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if a string contains a word in PHP?
提问by Lucas Matos
In SQL we have NOT LIKE %string%
在 SQL 中,我们有 NOT LIKE %string%
I need to do this in PHP.
我需要在 PHP 中执行此操作。
if ($string NOT LIKE %word%) { do something }
I think that can be done with strpos()
我认为可以做到 strpos()
But can't figure out how…
但是想不通怎么办……
I need exactly that comparission sentence in valid PHP.
我在有效的 PHP 中完全需要那个比较语句。
if ($string NOT LIKE %word%) { do something }
回答by Marc B
if (strpos($string, $word) === FALSE) {
... not found ...
}
Note that strpos()
is case sensitive, if you want a case-insensitive search, use stripos()
instead.
请注意,这strpos()
是区分大小写的,如果您想要不区分大小写的搜索,请stripos()
改用。
Also note the ===
, forcing a strict equality test. strpos CAN return a valid 0
if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.
还要注意===
, 强制进行严格的相等测试。0
如果 'needle' 字符串位于 'haystack' 的开头,strpos 可以返回一个有效值。通过强制检查实际布尔值 false(又名 0),您可以消除误报。
回答by TimWolla
Use strpos
. If the string is not found it returns false
, otherwise something that is not false
. Be sure to use a type-safe comparison (===
) as 0
may be returned and it is a falsy value:
使用strpos
. 如果未找到该字符串,则返回false
,否则返回false
。一定要使用类型安全的比较 ( ===
) ,因为它0
可能会返回,它是一个假值:
if (strpos($string, $substring) === false) {
// substring is not found in string
}
if (strpos($string, $substring2) !== false) {
// substring2 is found in string
}
回答by Vishnu Sharma
<?php
// Use this function and Pass Mixed string and what you want to search in mixed string.
// For Example :
$mixedStr = "hello world. This is john duvey";
$searchStr= "john";
if(strpos($mixedStr,$searchStr)) {
echo "Your string here";
}else {
echo "String not here";
}
回答by Ganesh
use
if(stripos($str,'job')){
// do your work
}