user5500750 user5500750 - 1 year ago 59
HTML Question

Wrap html tags around all text after the first word

How can I rewrite this code such that it wraps html tags around the last words after the first word;

preg_replace('/(?<=\>)\b\w*\b|^\w*\b/', '<span class="color_red">$0</span>', $atts['title']);

At the moment this regular expression will wrap tags around the first word in a string. I have tried this but it does not work;

preg_replace('/(?<=\>)\b\w*\b|^\w*\b/', '<span class="color_red">$1</span>', $atts['title']);

Here are some examples;

Efficiency <span class="color_red">solutions</span>
Renewable <span class="color_red">Energy Solutions</span>
Accidentally <span class="color_red">left the caps lock on and typed something</span>

Or please provide another solution that works.

Answer Source

To match everything after the first word until the last word boundary try such as


and replace with

<span class="color_red">$0</span>
  • \b match inital word boundary of first word
  • [\w'-]+ one or more word characters, single quote and hyphen in a character class
  • \W+ one or more non-word characters
  • \K resets beginning of the reported match
  • .*\b anything until the last word boundary (use with s-flag for making dot match newlines).

See this demo at regex101

(If you use utf-8 input add u flag for unicode regex to adjust \b, \w, \W)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download