1

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でしたが、これは失敗し、私はただ輪になって、これをどこから始めればよいのか本当にわかりません。そのようなブラックリストのアプローチは適切ではないことがほぼ確実です。または安全です。

4

1 に答える 1

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
   );
}
于 2012-04-13T16:58:15.217 に答える