Preg_replace BBCode Link

I have this bbcode:

[url=http://www.youtube.com/watch?v=h1bIEK1h150]If I offer you my soul[/url]

      

eg. How can I turn it into this:

<a href="http://www.youtube.com/watch?v=h1bIEK1h150" target="_blank">If I offer you my soul</a>

      

+3


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);

      

+5


source







All Articles