Preg_replace BBCode Link

坚强是说给别人听的谎言 提交于 2019-12-01 08:02:13

问题


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:


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


来源:https://stackoverflow.com/questions/9726369/preg-replace-bbcode-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!