Search code examples
phpcodeigniterexplodesubstr

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


I need to print characters which come before the fifth <br> in a PHP string.

e.g. The string is:

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>

Out of above string I want to print the characters which come before the fifth <br>. The output should be:

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

I tried as below but it prints only the first line and does not work as required

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

Solution

  • If you cannot guarantee there will always be exactly 5 occurrences of <br> in your string, here's a more flexible non-regex solution which will give you everything up to a possible 5 occurrences:

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

    It's not clear if you want to keep any trailing <br> occurrences if there are less than 5, but if you want to always end the string before a <br> you can ensure they get removed by adding a final line:

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