考虑:

$a = 'How are you?';

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

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


当前回答

也许你可以这样做:

<?php
    findWord('Test all OK');

    function findWord($text) {
        if (strstr($text, 'ok')) {
            echo 'Found a word';
        }
        else
        {
            echo 'Did not find a word';
        }
    }
?>

其他回答

现在,使用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')。

可以通过三种不同的方式完成:

 $a = 'How are you?';

1-stristr()

 if (strlen(stristr($a,"are"))>0) {
    echo "true"; // are Found
 } 

2-strpos()

 if (strpos($a, "are") !== false) {
   echo "true"; // are Found
 }

3-preg_match()

 if( preg_match("are",$a) === 1) {
   echo "true"; // are Found
 }

您需要使用相同/不相同的运算符,因为strpos可以返回0作为其索引值。如果您喜欢三元运算符,请考虑使用以下运算符(我承认这有点倒退):

echo FALSE === strpos($a,'are') ? 'false': 'true';

查看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.";
}

可以使用以下函数检查字符串:

function either_String_existor_not($str, $character) {
    return strpos($str, $character) !== false;
}