I'm trying to turn a string like
HELLO NOGDOG
to
<span...>H</span>ELLO <span...>N</span>OGDOG
with preg_replace() but so far have only given myself a headache...
Please help, & thank you
One possible implementation would be:
$str = 'HELLO NOGDOG'; $str = preg_replace('/(\S)(\S+)/', '<span>$1</span>$2', $str); echo htmlspecialchars($str);
thank you,
But I'm also looking for it to work if the number of words are dynamic and unknown,
As far as I can tell, that works for an arbitrary number of words, though it defines "word" as "sequence of two or more non-whitespace characters". If you want "one or more", then change (\S+) to (\S*).
thank you so much, you've saved my day
No problem, though note that how I defined a "word" may not be the same as how you define a word, so if your definition is different, you must make the appropriate changes.
Remember to mark this thread as resolved (if it is) using the thread tools.
Another option, just because TMTOWTDI.
$string = preg_replace('/\b\w/', "<span>$0</span>", $string);
NogDog;10887414 wrote:Another option, just because TMTOWTDI.
TMTOWTDI = ?? (WTF? LOL) 😃
EDIT - After some pondering, does it mean: To Me The Only Way To Do It?
There's More Than One Way To Do It
Ah... that makes sense.