考虑:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?


当前回答

您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。

<?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样本

其他回答

if (preg_match('/(are)/', $a)) {
   echo 'true';
}

我认为一个好主意是使用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';
}

如果只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。改用strpos()或strstr(),因为它们会更快。(http://in2.php.net/preg_match)

if (strpos($text, 'string_name') !== false){
   echo 'get the string';
}

特定字符串的另一种解决方案:

$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
    echo true;
}

也可以使用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')。