PHP-如何检查字符串是否包含子字符串并打印它[重复]

问题描述 投票:1回答:3

这个问题在这里已有答案:

我需要使用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
php database
3个回答
3
投票

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

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

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


0
投票

在PHP中,strpos在匹配时返回子字符串的起始索引,否则返回False。因此,当“快乐”从索引0开始时,strpos返回0制作你的if if check 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++;
        }
}

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);
© www.soinside.com 2019 - 2024. All rights reserved.