2012-04-13 68 views
1

我想检测一个URI是否位于字符串中,正确清理它并使用正确的锚标签输出。检测URI是否在字符串中并输出锚点

即用户输入:

Check out our profile on facebook! 
https://facebook.com/ourprofile 

and our twitter! 
twitter.com/#!/ourprofile 

and email us! 
[email protected] 

有没有一种方法来确定,有位于字符串中的URI,消毒不安全字符,并且正确地输出一个安全锚?

所以输出会是:

Check out our profile on facebook! 
<a href="https://www.facebook.com/ourprofile">https://www.facebook.com/ourprofile</a> 

and our twitter! 
<a href="http://www.twitter.com/#!/ourprofile">twitter.com/#!/ourprofile</a> 

and email us! 
<a href="mailto:[email protected]">[email protected]</a> 

的想法,我脑子里想的是使用preg_match和简单的preg_replace去除不安全字符,但这种失败我和IM在圈子只是去,我真的不知道从哪里开始,就像我几乎可以肯定的那样,黑名单方法是不适当的或安全的。

+1

看起来你正在寻找http://stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior – MrCode 2012-04-13 16:54:06

回答

3

我在experts-exchange.com找到了此新程序。希望,它可以帮助:

function make_links($text) 
{ 
    return preg_replace(
    array(
     '/(?(?=<a[^>]*>.+<\/a>) 
      (?:<a[^>]*>.+<\/a>) 
      | 
      ([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+) 
     )/iex', 
     '/<a([^>]*)target="?[^"\']+"?/i', 
     '/<a([^>]+)>/i', 
     '/(^|\s)(www.[^<> \n\r]+)/iex', 
     '/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+) 
     (\\.[A-Za-z0-9-]+)*)/iex' 
     ), 
    array(
     "stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\">\\2</a>\\3':'\\0'))", 
     '<a\\1', 
     '<a\\1 target="_blank">', 
     "stripslashes((strlen('\\2')>0?'\\1<a href=\"http://\\2\">\\2</a>\\3':'\\0'))", 
     "stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))" 
     ), 
     $text 
    ); 
} 
相关问题