代码之家  ›  专栏  ›  技术社区  ›  Alec Smart

过滤链接+笑脸的用户输入(段落)

  •  0
  • Alec Smart  · 技术社区  · 17 年前

    我正在研究某种现有的过滤器,它可以清理用户输入以避免XSS。也许我可以使用htmlspecialchars来实现这一点。但同时我希望能够解析所有链接(应该匹配a.com、www.a.com和 http://www.a.com 如果是的话 http://www.aaaaaaaaaaaaaaaaaaaaaaaaaa.com 然后它应该显示为aaa..a.com)、电子邮件和笑脸。

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

    谢谢你抽出时间。

    2 回复  |  直到 17 年前
        1
  •  0
  •   Bart Kiers    17 年前

    从字符串(尝试!)获取链接的简单方法如下:

    $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
            )
    
    )
    

    在匹配(可能的!)URL后,您可以清理列表:即删除无效的URL,如“aaa..a.com”,并缩短很长的URL,如“aaa..a.com” http://www.aaaaaaaaaaaaaaaaaaaaaaaaaa.com '.

    我不建议把所有东西都塞进一个大的、无法维护的正则表达式中。分步做。

    祝你好运

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

        2
  •  0
  •   eyescream    16 年前

    http://www.php.net/manual/en/book.bbcode.php (需要php 5.2.0或更高版本,除非您可以从PECL安装)

    推荐文章