如何反转函数如何检查字符串是否包含PHP中的特定单词?
if (strpos($a,'are') !== false) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)
因此,它呼应true,如果are是不中找到$a.
Rot*_*ham 31
这里的代码:
if (strpos($a, 'are') !== false) {
// The word WAS found
}
Run Code Online (Sandbox Code Playgroud)
表示在字符串中找到单词WAS.如果删除NOT(!)运算符,则表示已撤消该条件.
if (strpos($a, 'are') === false) {
// The word was NOT found
}
Run Code Online (Sandbox Code Playgroud)
===非常重要,因为如果单词'are'位于字符串的最开头,strpos将返回0,并且因为0松散等于FALSE,你会因为找出错误而感到沮丧.===运算符使得它非常字面地检查结果是否为布尔值false而不是0.
举个例子,
if (!strpos($a, 'are')) {
// String Not Found
}
Run Code Online (Sandbox Code Playgroud)
如果$ a ="你今晚过来了吗?",这段代码会说字符串'are',因为'are'的位置是0,字符串的开头.这就是为什么使用===错误检查是如此重要.
使用 strstr():
if (!strstr($var, 'something')) {
// $var does not contain 'something'
}
Run Code Online (Sandbox Code Playgroud)
或 strpos():
if (strpos($var, 'something') === false) {
// $var does not contain 'something'
}
Run Code Online (Sandbox Code Playgroud)
或者 str i pos() 如果你想要不区分大小写的搜索。
strpos()快一点
当你看到它时,你可能会踢自己......
if (!strpos($a,'are') !== false) {
echo 'true';
}
Run Code Online (Sandbox Code Playgroud)