PHP-如何检查字符串是否包含子字符串并打印

时间:2019-04-15 03:16:55

标签: php database

我需要使用PHP打印出包含给定子字符串“ Happy”的所有字符串。

$t包含所有输入数据。我尝试这样做,但无法达到预期的输出。

请提供有关如何解决此问题的建议。预先感谢。

$i = 1;
while ($t = dbNext($r)) {
        $temp = strtolower($t[0]);
        if(strpos($temp, 'happy')){
                echo "$i - $t[0]";
                echo "\n";
                $i++;
        }
}

输入:

1. Happy Gilmore
2. The Fast and the Furious
3. Happy, Texas
4. The Karate Kid
5. The Pursuit of Happyness
6. Avengers: End Game
7. Happy Feet
8. Another Happy Day

预期输出:

1. Happy Gilmore
2. Happy, Texas
3. The Pursuit of Happyness
4. Happy Feet
5. Another Happy Day

我得到的输出:

1. The Pursuit of Happyness
2. Another Happy Day

3 个答案:

答案 0 :(得分:3)

strpos如果不匹配,则返回false,但如果字符串与第一个字符匹配,则返回0。因此,您需要严格检查strpos的结果以查看是否匹配,因为在布尔上下文中0false相同:

if (strpos($temp, 'happy') !== false) {

请注意,您实际上可以使用不区分大小写的stripos,然后就不需要调用strtolower

答案 1 :(得分:0)

在PHP中,strpos在匹配时返回子字符串的起始索引,否则返回False。因此,当“ Happy”从索引0开始时,strpos返回0,从而使if校验为false。做这样的事情:

$i = 1;
while ($t = dbNext($r)) {
        $temp = strtolower($t[0]);
        $res = strpos($temp, 'happy');
        if(gettype($res) == "integer" && $res >= 0){
                echo "$i - $t[0]";
                echo "\n";
                $i++;
        }
}

答案 2 :(得分:0)

$str = 'this is the string';
$flag = 'i';

//Will return false if there is no $flag or the position of the first occurrence
$test = strpos($str, $flag); // returns 2

if( $test !== false ){

    echo substr($str, $test); //is is the string


}else{
    //There is no i in the string
}

使用循环

$input = array(
    'Happy Gilmore',
    'The Fast and the Furious',
    'Happy, Texas',
    'The Karate Kid',
    'The Pursuit of Happyness',
    'Avengers: End Game',
    'Happy Feet',
    'Another Happy Day',
);


$flag = 'happy';

//Loop 
foreach( $input AS $i ){

    //Test for occurrence
    $test = stripos($i, $flag); // returns false or number

    if( $test !== false ){


        $values[] = $i; //Returns the full string - alternatively you could use substr to extract happy or even explode using happy to count the amount of times it occurs


    }else{
        //There is no $flag in the string
    }
}

print_r($values);