打印 php 字符串中第五个 <br> 之前的字符

Print characters which come before the fifth <br> in php string

我需要打印 PHP 字符串中第五个 <br> 之前的字符。

例如字符串是:

A silly young Cricket <br> 
Accustomed to sing  <br><br> 
Through warm sunny weather <br>
of winter summer and spring <br><br>
Now that you forget the poem<br>
having memorised it 18 years back in school<br><br>

在上面的字符串中,我想打印第五个 <br> 之前的字符。输出应该是:

A silly young Cricket <br>  Accustomed to sing  <br><br>  Through warm sunny weather <br> of winter summer and spring

我试过如下但它只打印第一行并且不能按要求工作

<?php
$trer = 'the above string in example';
$arrdr = explode("<br>", $trer, 5);
$pichka = array_shift($arrdr);
echo $pichka; 
?>

正如我在你的字符串中看到的那样,你在某些行中有两个 br 标记,在爆炸中你用它拆分了字符串,这可能会给你带来问题

试试这个,让我知道结果:

$string = 'A silly young Cricket <br> 
Accustomed to sing  <br><br> 
Through warm sunny weather <br>
of winter summer and spring <br><br>
Now that you forget the poem<br>
having memorised it 18 years back in school<br><br>';

$needles = explode(chr(10), $needles, 5);

print_r($needles);

“chr(10)”函数 return \n 字符。可以直接用\n

一种正则表达式方法是使用惰性点来谨慎匹配前五个 <br> 标签:

$input = "A silly young Cricket <br> \nAccustomed to sing  <br><br> \nThrough warm sunny weather <br>\nof winter summer and spring <br><br>\nNow that you forget the poem<br>\nhaving memorised it 18 years back in school<br><br>";
preg_match("/^.*?<br>.*?<br>.*?<br>.*?<br>.*?(?=<br>)/s", $input, $matches);
print_r($matches[0]);

这会打印:

A silly young Cricket <br> 
Accustomed to sing  <br><br> 
Through warm sunny weather <br>
of winter summer and spring 

请注意,在正则表达式模式中,我使用 /s 开关来匹配使用全点模式,以便 .* 匹配换行符。

如果您不能保证 <br> 在您的字符串中总是恰好出现 5 次,这里有一个更灵活的 non-regex 解决方案,它将为您提供最多出现 5 次的所有内容:

$split = array_map(function ($part) {
    return implode('<br>', $part);
}, array_chunk(explode('<br>', $str), 5));
$output = array_shift($split);

如果少于 5 个,是否要保留任何尾随出现的 <br> 尚不清楚,但如果您想始终在 <br> 之前结束字符串,您可以确保它们被删除添加最后一行:

$output = preg_replace('/(<br>)+$/s', '', $output);