I have a problem with my RegEx. I want to translate a BBCode link tag like:
[link=www.stackoverflow.com]Stack-Overflow[/link]
into a HTML link:
<a href='www.stackoverflow.com'>Stack-Overflow</a>.
In my string it’s possible to make more than one link in BBCode.
I also need a function to translate the HTML back to BBCode.
My functions are:
-
BBCode To HTML:
$Text = preg_replace( '/\[link=([^ ]+).*\](.*)\[\/link\]/', '<a href="$1">$2</a>', $Text ); -
HTML To BBCode:
$Text = preg_replace( '/\<a href="([^ ]+).*\">(.*)\<\/a\>/Usi', '[link=$1]$2[/link]', $Text );
My problem with these functions is when I have more than one link to convert, it doesn’t work.
And when I have one link translated to HTML and I want to translate back, I have only the first character of the link.
As for your first problem,
*is greedy, so it catches everything between the first and last links. A simple solution is to use a non-greedy qualifier, or to not allow[]in your groups:Similarly, for the other way around:
Here’s the non-greedy version. It allows
[]in links, and is even shorter: