如何检查字符串是否包含特定文本

php
2022-08-30 07:34:36
<?php
$a = '';

if($a exist 'some text')
    echo 'text';
?>

假设我有上面的代码,如何编写语句?if($a exist 'some text')


答案 1

使用功能:http://php.net/manual/en/function.strpos.phpstrpos

$haystack = "foo bar baz";
$needle   = "bar";

if( strpos( $haystack, $needle ) !== false) {
    echo "\"bar\" exists in the haystack variable";
}

在您的情况下:

if( strpos( $a, 'some text' ) !== false ) echo 'text';

请注意,我使用运算符(而不是或甚至只是)是因为PHP处理返回值的“真实”/“虚假”性质。!==!= false== trueif( strpos( ... ) ) {strpos

从 PHP 8.0.0 开始,您现在可以使用str_contains

<?php
    if (str_contains('abc', '')) {
        echo "Checking the existence of the empty string will always 
        return true";
    }

答案 2

空字符串是假的,所以你可以只写:

if ($a) {
    echo 'text';
}

虽然如果你要询问该字符串中是否存在特定的子字符串,你可以用它来做到这一点:strpos()

if (strpos($a, 'some text') !== false) {
    echo 'text';
}

推荐