URL-BBCode Regex

家住魔仙堡 提交于 2019-12-06 12:10:14

You can use this pattern:

$pattern = '~\[url(?|=[\'"]?([^]"\']+)[\'"]?]([^[]+)|](([^[]+)))\[/url]~';
$replacement = '<a href="$1">$2</a>';

$result = preg_replace($pattern, $replacement, $subject);

The idea is to preserve the groups numbers for each branch of the alternation using the branch reset feature. In this way, group 1 contains always the url and group 2 the link description. When there is no description, the url is used in place, that's why the url is twice enclosed in a capture group for the second branch.

Try this, it will work

<?php
  $urlsearch  = "(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?";
  $text = preg_replace( "/\[url\]($urlsearch)\[\/url\]/", "<a href=\"$1\">$1</a>", $text );
  $text = preg_replace( "(\[url\=[\"']?($urlsearch)[\"']?\](.+?)\[/url\])", "<a href=\"$1\">$5</a>", $text );

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