I have a string of a comment that looks like this:
**@First Last** rest of comment info.
What I need to do is replace the ** with <b>
and </b>
so that the name is bold.
I currently have this:
$result = preg_replace('/**/i', '<b>$0</b>', $comment);
But that results in:
"<b>**</b>@First Last<b>**</b> rest of comment info"
Which is obviously not what I need. Does anyone have any suggestions on how to achieve this?
Advertisement
Answer
A better idea would be to use a markdown parser library which does this for you.
Improper use of the regular expressions can lead to security vulnerabilities with unclosed tags etc..
However, a simple approach could be this:
$result = preg_replace('/**(.+)**/sU', '<b>$1</b>', $comment);
The U means ungreedy and takes the first possible match.
The s modifies .
to be any character, including newline.
(see modifiers page)
This also works with an example text like this:
**@First Last** rest of comment info **also bold**. The next line also **has a bold example**. This spans **two lines**.
I am sure there are counter examples which are broken with this. Again, please use a proper markdown library to do this for you (or copy their implementation if the LICENSE allows it).