phpregexreplacetext-parsingbbcode

Convert BBCode [link='www.example.com]example[/link] into HTML <a href="www.example.com">example</a>


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:

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.


Solution

  • 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:

    \[link=([^ \[\]]+)\]([^\[\]]*)\[\/link\]
    

    Similarly, for the other way around:

    <a href="([^ "]+)">([^<]*?)\<\/a\>
    

    Here's the non-greedy version. It allows [] in links, and is even shorter:

    \[link=([^ ]*?)\](.*?)\[\/link\]