检测 URI 是否位于字符串和输出定位点内


Detect if a URI is within a string and output anchor

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

即,用户输入:

Check out our profile on facebook!
https://facebook.com/ourprofile
and our twitter!
twitter.com/#!/ourprofile
and email us!
ourprofile@stack.com

有没有办法确定字符串中是否存在 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:ourprofile@stack.com">ourprofile@stack.com</a>

我想到的想法是使用preg_match简单的preg_replace来删除不安全的字符,但这让我失望了,我只是在兜圈子,我真的不知道从哪里开始,因为我几乎可以肯定这样的黑名单方法是不合适或不安全的。

我在 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
   );
}