考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
if (preg_match('/(are)/', $a)) {
echo 'true';
}
其他回答
Use:
$text = 'This is a test';
echo substr_count($text, 'is'); // 2
// So if you want to check if is exists in the text just put
// in a condition like this:
if (substr_count($text, 'is') > 0) {
echo "is exists";
}
您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。
<?php
$grass = "This is pratik joshi";
$needle = "pratik";
if (stripos($grass,$needle) !== false) {
/*If i EXCLUDE : !== false then if string is found at 0th location,
still it will say STRING NOT FOUND as it will return '0' and it
will goto else and will say NOT Found though it is found at 0th location.*/
echo 'Contains word';
}else{
echo "does NOT contain word";
}
?>
在这里,stripos在不考虑箱子(小/帽)的情况下,在heystack中找到了针头。
带输出的PHPCode样本
使用strstr()和stristr(()从字符串中查找单词出现的另一个选项如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
如果要检查字符串是否包含多个特定单词,可以执行以下操作:
$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat");
$string = "a string with the word ivoire";
$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches);
if ($matchFound) {
echo "a bad word has been found";
}
else {
echo "your string is okay";
}
例如,这对于在发送电子邮件时避免垃圾邮件非常有用。
另一个选项是使用strstr()函数。类似于:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。