Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

php - Smarty modifier to add hyperlinks doesn't work when text is in parentheses

I'm using a Smarty modifier to turn a plaintext link into a proper hyperlink, I'm using a Smarty modifier for this as it's for a website that utilizes user content, in which only some areas are allowed to have hyperlinks.

This is the modifier:

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

The code for the modifier was shared on another website. It works fine but doesn't work when the plaintext link is in parentheses, any help would be appreciated, thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One extracted PCRE regex:

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

regex tested on regex101.com with url (www.example.com/test/test.html)

collection group2 -> www.example.com/test/test.html

So the following should work:

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

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

Explanation: I have added

)? 

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...