考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
如果搜索不区分大小写,则使用strstr()或stristr(。
其他回答
您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。
<?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()函数。类似于:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。
如果只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。改用strpos()或strstr(),因为它们会更快。(http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
我在这方面遇到了一些麻烦,最后我选择了自己的解决方案。不使用正则表达式引擎:
function contains($text, $word)
{
$found = false;
$spaceArray = explode(' ', $text);
$nonBreakingSpaceArray = explode(chr(160), $text);
if (in_array($word, $spaceArray) ||
in_array($word, $nonBreakingSpaceArray)
) {
$found = true;
}
return $found;
}
您可能会注意到,前面的解决方案并不是对另一个用作前缀的单词的答案。为了使用您的示例:
$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";
对于上面的示例,$a和$b都包含$c,但您可能希望函数告诉您,只有$a包含$c。
许多使用subst_count的答案会检查结果是否大于0。但由于if语句将零视为false,因此可以避免该检查并直接写入:
if (substr_count($a, 'are')) {
若要检查是否不存在,请添加!操作员:
if (!substr_count($a, 'are')) {