Preg_replace BBCode Link

2019-02-19 04:41发布

I have this bbcode:

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

for example. How can I turn this into this:

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

1条回答
我命由我不由天
2楼-- · 2019-02-19 05:01

You need a regular expression. Taking into account that bbcode can have a text URL or only the URL, you will need two statements:

$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're parsing bbcode from PHPBB, it can have a unique user identifier:

$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);
查看更多
登录 后发表回答