考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
特定字符串的另一种解决方案:
$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
echo true;
}
也可以使用strpos()函数。
其他回答
另一个选项是使用strstr()函数。类似于:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。
这里有一个小的实用函数,在这种情况下很有用
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
使用strstr()和stristr(()从字符串中查找单词出现的另一个选项如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
如果搜索不区分大小写,则使用strstr()或stristr(。
也许你可以这样做:
<?php
findWord('Test all OK');
function findWord($text) {
if (strstr($text, 'ok')) {
echo 'Found a word';
}
else
{
echo 'Did not find a word';
}
}
?>