PHP REGEX匹配给定URL的域名

时间:2013-07-19 11:40:14

标签: php regex

我想要的是域名是否存在于字符串中。

我的问题的例子是

+----------------------------------------------+-----------------------+
| input                                        | output                |
+----------------------------------------------+-----------------------+
| http://www.example.com/questions/ask         | match or true         |
| http://example.com/check                     | match or true         |
| http://www.google.com/ig/moduleurl           |
|    =http%3A%2F%2Fwww.example.com%2Fquestion  | false                 |
| http://example.com/search/%25C3%25A9t%25     | match true            |
+----------------------------------------------+-----------------------+

任何帮助都会很明显

由于

3 个答案:

答案 0 :(得分:4)

这里不需要正则表达式IMO:

使用parse_url() check man here,你可以获得域名,主机......你想要的,真的。加上(极快)字符串函数:

if (strstr(parse_url($input,PHP_URL_HOST),'example.com'))
{
    echo $input.' is a match';
}

但您方案中最快捷的方式是:

$match = strpos($input, 'example.com');
$match = $match !== false && $match <= 12 ? true : false;
//12 is max for https://www.example.com

你甚至不需要!!(...);,但这样你就可以为$match分配一个布尔值

但是第一个建议看起来仍然更清晰,更具可读性。

如果以您要查找的主机开头的字符串无效:

$match = strpos($input, 'example.com');
$match = !!($match && $match < 13);

是我能想到的最快的方法

答案 1 :(得分:2)

您可以使用此模式执行此操作:

$pattern = '~^(?:ht|f)tps?://[^/]*?(?<=\.|/)'.preg_quote($domain).'(?=/|$)~i';

答案 2 :(得分:0)

最好使用parse_url function而不是解析整个网址:

$arr = parse_url($url);
$host = $arr['host'];

// now just match the hostname
if (preg_match('#^(?:[^.]+\.)*example\.com$#i', $host, $arr))
    var_dump($arr); // or return true;

这个正则表达式也可以起作用:

if (preg_match('#^https?://(?:[^.]+\.)*example\.com/#i', $url, $arr))
   var_dump($arr); // return true;