Regular Expressions: preg_replace only does one per line.
Posted on 2004-11-17
I am writing a little hack for a Wiki that enables highlighting of text using a background color. I use preg_replace to replace text delimited by ++ to insert the appropriate span. It works fine except for one thing, when there are multiple words highlighted in the same line, it only replaces the first and the last ++, leaving the middle ones intact and in effect it highlights the whole line from the first ++ to the last (with ++ as plain text in the middle). Here's the sample code
$text = "test ++highlight!!++ test test test ++test++ highlight";
echo preg_replace('/\+\+(.*)\+\+/','<span style="background-color: #FFFF00">\\1</span>', $text);
In this case, the first occurence of "highlight" and the last occurence of "test" should be highlighted (ie <span...>highlight</span>). If I insert a \n between the two words somewhere it works as it should.
I am not much of a regular expressions expert so could someone help me fix this one?