Created
February 21, 2020 09:53
-
-
Save morgyface/e195d6b7638d8ae296513540cdc6dd22 to your computer and use it in GitHub Desktop.
PHP | wrap the last word of a string in span
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| } |
Author
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
That's much neater @elron, thank you!
preg_replacealways looks messy.