Preg_replace BBCode Link

I have this bbcode:

[url=]If I offer you my soul[/url]


eg. How can I turn it into this:

<a href="" target="_blank">If I offer you my soul</a>



source to share

1 answer

You need a regular expression. Whereas bbcode can have a text url or just a url, you need two operators:

$message = preg_replace('@\[url=([^]]*)\]([^[]*)\[/url\]@', '<a href="$1">$2</a>', $message);
$message = preg_replace('@\[url\]([^[]*)\[/url\]@', '<a href="$1">$1</a>', $message);


Also, if you are parsing bbcode from PHPBB, it can have a unique user id:

$uid = '[0-9a-z]{5,}';
$message = preg_replace('@\[url=([^]]*):'. $uid . '\]([^[]*)\[/url:'. $uid . '\]@', '<a href="$1">$2</a>', $message);
$message = preg_replace('@\[url:'.         $uid . '\]([^[]*)\[/url:'. $uid . '\]@', '<a href="$1">$1</a>', $message);




All Articles