【问题标题】:Smarty modifier to add hyperlinks doesn't work when text is in parentheses当文本在括号中时,添加超链接的 Smarty 修饰符不起作用
【发布时间】:2021-01-12 16:12:22
【问题描述】:

我正在使用 Smarty 修饰符将纯文本链接转换为正确的超链接,为此我使用 Smarty 修饰符,因为它适用于使用用户内容的网站,其中仅允许某些区域具有超链接。

这是修饰符:

function smarty_modifier_dolink($text)
{
   $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
   $ret = ' ' . $text;
   $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
   $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
   //$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
   $ret = substr($ret, 1);
   return $ret;
}
?>

修改器的代码已在另一个网站上共享。它工作正常,但当明文链接在括号中时不起作用,任何帮助将不胜感激,谢谢!

【问题讨论】:

标签: php regex smarty modifier


【解决方案1】:

一个提取的 PCRE 正则表达式:

(^|[\n ])\(?((www|ftp)\.[\w\#$%&~\/.\-;:=,?@\[\]+]*)\)?   

正则表达式在 regex101.com 上测试,带有 url (www.example.com/test/test.html)

集合组2 -> www.example.com/test/test.html

所以以下应该可以工作:

   $ret = preg_replace("#(^|[\n ])\(?((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)\)?#is", "\\1<a href=\"http://\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);

$ret = preg_replace("#(^|[\n ])(?([\w]+?://[\w#$%&~/.-;:=,?@[]+ ]*)(?#is", "\1\2", $ret);

说明:我添加了

\)? 

/) for a bracket and ? for optional  at the positions where i suggested your brackets to be.   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多