Search code examples
phphtmlarraysexplode

Put last two words in different span - PHP


I can't figure out the following: I have strings returned from which I want to put the first few words in some html tag and than the last two separately like this:

<p>This is a <span class="someclass">returned string</span></p>

I know I can explode the string into an array and make every word an iteration, but than I can only figure out how to put the first two words in a different html tag, and I want the last two. Each string can have a different number of words.

I was thinking of doing something with array count, like:

$string = this is a returned string;
$words = explode(" ", $string);
$count = count($words); // $words in this case is 5
$amountofwordsbeforespan = $count - 2;
echo '<p>'.$amountofwordsbeforespan.'<span class="somethingtostyleit">'.SOMETHING THAT PUTS THE LAST TWO HERE.'</span></p>';

But I think there should be an easier way.

Does someone know what is the cleanest way to accomplish this?


Solution

  • Another way using array_splice(),

    <?php
    $string = 'this is a returned string';
    $words = explode(" ", $string ); 
    $last_two_word = implode(' ',array_splice($words, -2 )); 
    $except_last_two = implode(' ', $words);
    $expected = '<p>'.$except_last_two.' <span class="someclass">'.$last_two_word.'</span></p>';
    echo $expected;
    ?>
    

    DEMO: https://3v4l.org/d3DYq