wildhaber
wildhaber

Reputation: 1661

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.

Upvotes: 1

Views: 178

Answers (2)

slebetman
slebetman

Reputation: 113906

Your problem is with the greedy .* Use ? to make it non greedy.

$Text = preg_replace(
    '/\[link=([^ ]+).*?\](.*?)\[\/link\]/',
    '<a href="$1">$2</a>',
    $Text
);

Upvotes: 0

Kobi
Kobi

Reputation: 138027

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\]

Upvotes: 5

Related Questions