【问题标题】:Detect if a URI is within a string and output anchor检测 URI 是否在字符串中并输出锚点
【发布时间】:2012-04-13 15:43:42
【问题描述】:

我想检测 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 来删除不安全的字符,但这让我失望了,我只是在兜圈子,我真的不知道从哪里开始,因为我几乎可以肯定诸如此类的黑名单方法是不适当或不安全的。

【问题讨论】:

标签: php security uri anchor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多