1

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

我的问题的例子是

+----------------------------------------------+-----------------------+
| 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            |
+----------------------------------------------+-----------------------+

任何帮助都将是可观的

谢谢

4

3 回答 3

4

No need for regex here IMO:

using parse_url() check man here, you can get the domain, host... all you want, really. Coupled with the (extremely fast) string functions:

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

But the quickest way in your scenario would be:

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

You wouldn't even need the !!(...);, but that's just so you can se that $match is being assigned a boolean

But the first suggestion still looks cleaner and more readable, to my eye.

If a string beginning with the host you're looking for isn't valid either:

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

Is the fastest approach I can think of

于 2013-07-19T11:43:07.403 回答
2

You can do it using this pattern:

$pattern = '~^(?:ht|f)tps?://[^/]*?(?<=\.|/)'.preg_quote($domain).'(?=/|$)~i';
于 2013-07-19T11:44:00.370 回答
0

最好使用parse_url 函数而不是解析整个 URL:

$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;
于 2013-07-19T11:45:07.783 回答