Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created February 21, 2020 09:53
Show Gist options
  • Select an option

  • Save morgyface/e195d6b7638d8ae296513540cdc6dd22 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/e195d6b7638d8ae296513540cdc6dd22 to your computer and use it in GitHub Desktop.
PHP | wrap the last word of a string in span
<?php
// Function to wrap last word in span
function last_word_wrap($string, $class = null) {
$span = '<span';
if( $class ) {
$span .= ' class="' . $class . '"';
}
$span .= '>';
$wrapped = preg_replace('/\s(\S*)$/', ' ' . $span . '$1', $string);
$wrapped .= '</span>';
return $wrapped;
}
@elron
Copy link

elron commented May 23, 2020

Here's my try:

<?php
/**
 * Wrap last word with span
 * @author: Elron
 * https://stackoverflow.com/questions/18612872/get-the-last-word-of-a-string
 */
function wrap_last_word($string) {
    // Breaks string to pieces
    $pieces = explode(" ", $string);

    // Modifies the last word
    $pieces[count($pieces)-1] = '<span class="is-last-word">' . $pieces[count($pieces)-1] . '</span>';

    // Returns the glued pieces
    return implode(" ", $pieces);
}

wrap_last_word('hello this is wrapped');
// returns this:
// hello this is <span class="is-last-word">wrapped</span>

@morgyface
Copy link
Author

That's much neater @elron, thank you! preg_replace always looks messy.

@elron
Copy link

elron commented May 23, 2020

Thanks!
I wonder if there any performance advantage for preg_replace or explode/implode.
Anyway, I'm using it for short strings so it should be fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment