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;
}
@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