过滤链接+表情符号的用户输入(段落)

时间:2009-10-09 05:03:40

标签: php regex filtering

我正在研究某种现有的过滤器,它可以清理用户输入以避免XSS。可能我可以使用htmlspecialchars。但与此同时,我希望能够解析所有链接(应该匹配a.com,www.a.com和http://www.a.com,如果它是http://www.aaaaaaaaaaaaaaaaaaaaaaaaaa.com,那么它应该显示为aaa .. a.com),电子邮件和表情。

我想知道最好的方法是什么。我目前正在使用带有一些正则表达式的php函数,但很多时候正则表达式都失败了(因为链接识别不正确等)。我想要一些与谷歌聊天中使用的解析器非常相似的东西(甚至是a.com的工作)。

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

一种简单的方法(尝试!)从字符串中获取链接是这样的:

$text = 'I am looking at some sort of existing filter which can sanitize 
the user input to avoid XSS. Probably I can use htmlspecialchars for that. 
But at the same time I want to be able to parse all links (should match 
a.com, www.a.com and http://www.a.com and if it is 
http://www.aaaaaaaaaaaaaaaaaaaaaaaaaa.com then it should display it 
as aaa..a.com), e-mails and smileys.

I am wondering what is the best way to go about it. I am currently using 
a php function with some regex, but many times the regex simply fails 
(because of link recognition is incorrect etc.). I want something very 
similar to the parser used during Google Chat (even a.com works).';

preg_match_all('/\S+\.(?:com|org|net)/i', $text, $urls);

print_r($urls);

产生:

Array
(
    [0] => Array
        (
            [0] => a.com
            [1] => www.a.com
            [2] => http://www.a.com
            [3] => http://www.aaaaaaaaaaaaaaaaaaaaaaaaaa.com
            [4] => aaa..a.com
            [5] => a.com
        )

)

在匹配(可能的!)网址后,您可以清理列表:即。删除像'aaa..a.com'这样的无效内容,并缩短非常长的网址,例如“http://www.aaaaaaaaaaaaaaaaaaaaaaaaaa.com”。

我不建议在一个庞大的,无法维护的正则表达式中塞满所有内容。分步进行。

祝你好运!

PS。不用说,你可以/应该自己扩展tld列表。 (?:com | org | net)就是一个例子。

答案 1 :(得分:0)

对于表情符号,您可能需要查看http://www.php.net/manual/en/book.bbcode.php(需要php 5.2.0或更高版本,除非您可以从PECL安装它)