I should start by saying that HTML operations are better done with a proper parser such as DOMDocument
. This particular problem is straightforward, so regular expressions may work without too much hocus pocus, but be warned :)
You can use look-around assertions; this frees you from having to restore the neighbouring strings during the replacement:
echo preg_replace('/(?<=^|<br \/>)[^:]+(?=:)/m', '<b>$0</b>', $str);
First, the look-behind assertion matches either the start of each line or a preceding <br />
. Then, any characters except the colon are matched; the look-ahead assertion makes sure it's followed by a colon.
The /m
modifier is used to make ^
match the start of each line as opposed to \A
which always matches the start of the subject string.