这个问题在这里已有答案:
我需要使用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中,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++;
}
}
$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);