繁体   English   中英

匹配文本中URL的方法

[英]Method for matching URLs in text

在PHP中,建议使用什么方法来匹配文本正文中的所有URL(即,形式$ _POST textarea而不是一个'word'字符串)?

我正在寻找一种与大多数URL匹配的方法,而不是与超标准兼容的通用方法。 我喜欢匹配的示例:

理想情况下,将结果放入关联数组中。

我了解parse_url不太适合。 而且我听说使用正则表达式充满了问题。 但是我也听说filter_var有很多问题,其中最重要的是需要一个方案。 你们都使用什么技术?

谢谢

就您而言,我认为针对多个正则表达式进行测试是可行的方法。

以下是一些与www.google.com匹配的示例正则表达式:

  • /^google[.]com/
  • /^http:\\/\\/www[.]google[.]com/

它将提取文本中所有上述网址。

<?php

$string='http://www.google.com?q=1000
http://google.com?xlkd=0
www.google.com?asdfsdf=asdf
google.com?234324';


preg_match_all('#\b(?:http(?:s)?:\/\/)?(?:www\.)??[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $string, $match);

echo "<pre>";
print_r($match);

输出为:

Array
(
    [0] => Array
        (
            [0] => http://www.google.com?q=1000
            [1] => http://google.com?xlkd=0
            [2] => www.google.com?asdfsdf=asdf
            [3] => google.com?234324
        )

    [1] => Array
        (
            [0] => 0
            [1] => 0
            [2] => f
            [3] => 4
        )

)

希望对您有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM