How do I check if a string contains a specific word?
Consider:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are')
?
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';
}
Note that the use of !== false
is deliberate; 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')
.
You could use regular expressions, it's better for word matching compared to strpos as mentioned by other users it will also return true for strings such as fare, care, stare etc. This can simply be avoided in the regular expression by using word boundaries.
A simple match for are could look something like this:
$a = 'How are you?';
if (preg_match('/bareb/',$a))
echo 'true';
On the performance side, strpos is about three times faster and have in mind, when I did one million compares at once, it took preg match 1.5 seconds to finish and for strpos it took 0.5 seconds.
使用strpos功能:
if (strpos($a, 'are') !== false)
echo 'true';
链接地址: http://www.djcxy.com/p/222.html
下一篇: 如何检查一个字符串是否包含特定单词?