如何检查字符串是否包含特定单词? [英] How do I check if a string contains a specific word?
问题描述
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,写语句if ($a contains 'are')
的正确方法是什么?
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
推荐答案
您可以使用 strpos()
函数,用于查找另一个字符串中另一个字符串的出现:
You can use the strpos()
function which is used to find the occurrence of one string inside another one:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
请注意,!== false
的使用是有意的(!= false
和=== true
都不会返回期望的结果); strpos()
返回大海捞针字符串中针串开始的偏移量,或者如果找不到针,则返回布尔值false
.由于0是有效偏移量,而0是假",我们不能使用像!strpos($a, 'are')
这样的更简单的构造.
Note that the use of !== false
is deliberate (neither != false
nor === true
will return the desired result); strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
这篇关于如何检查字符串是否包含特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!