考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
可以使用以下函数检查字符串:
function either_String_existor_not($str, $character) {
return strpos($str, $character) !== false;
}
其他回答
如果要避免“虚假”和“真实”问题,可以使用subst_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
它比strpos慢一点,但它避免了比较问题。
现在,使用PHP 8,您可以使用str_contains执行此操作:
if (str_contains('How are you', 'are')) {
echo 'true';
}
RFC
PHP 8之前
您可以使用strpos()函数,该函数用于查找一个字符串在另一个字符串中的出现:
$haystack = 'How are you?';
$needle = 'are';
if (strpos($haystack, $needle) !== false) {
echo 'true';
}
请注意,使用!==false是故意的(!=false或==true都不会返回期望的结果);strpos()返回大海捞针字符串开始时的偏移量,如果找不到针,则返回布尔值false。由于0是有效的偏移量,0是“false”,因此我们不能使用更简单的构造,如!strpos($a,'are')。
可以使用以下函数检查字符串:
function either_String_existor_not($str, $character) {
return strpos($str, $character) !== false;
}
使用strstr()和stristr(()从字符串中查找单词出现的另一个选项如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>
使用stripos()使用不区分大小写的匹配:
if (stripos($string,$stringToSearch) !== false) {
echo 'true';
}