考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
我认为一个好主意是使用mb_stpos:
$haystack = 'How are you?';
$needle = 'are';
if (mb_strpos($haystack, $needle) !== false) {
echo 'true';
}
因为此解决方案区分大小写,并且对所有Unicode字符都是安全的。
但你也可以这样做(sauch的回应还没有):
if (count(explode($needle, $haystack)) > 1) {
echo 'true';
}
此解决方案对Unicode字符也区分大小写并安全。
此外,在表达式中不使用否定,这会增加代码的可读性。
以下是使用函数的其他解决方案:
function isContainsStr($haystack, $needle) {
return count(explode($needle, $haystack)) > 1;
}
if (isContainsStr($haystack, $needle)) {
echo 'true';
}
其他回答
现在,使用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 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。
短手版本
$result = 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';
?>