考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
查看strpos():
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'.";
} else {
echo "The string '$findme' was found in the string '$mystring',";
echo " and exists at position $pos.";
}
其他回答
您还可以使用内置函数strchr()和strrchr()以及多字节字符串mb_strchr(()和mb_strrchr(()的扩展。这些函数返回部分字符串,如果找不到,则返回FALSE。
strchr()-查找字符串的第一次出现(是strstr()的别名)。strrchr()-查找字符串中最后出现的字符。
另一个选项是使用strstr()函数。类似于:
if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}
注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。
if (preg_match('/(are)/', $a)) {
echo 'true';
}
您可以使用strstr函数:
$haystack = "I know programming";
$needle = "know";
$flag = strstr($haystack, $needle);
if ($flag){
echo "true";
}
不使用内置功能:
$haystack = "hello world";
$needle = "llo";
$i = $j = 0;
while (isset($needle[$i])) {
while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) {
$j++;
$i = 0;
}
if (!isset($haystack[$j])) {
break;
}
$i++;
$j++;
}
if (!isset($needle[$i])) {
echo "YES";
}
else{
echo "NO ";
}
短手版本
$result = false!==strpos($a, 'are');