regex - exclude a subdomain (preg_match)

霸气de小男生 提交于 2019-12-11 04:15:45

问题


I'm want to match a domain (with preg_match) but I want to exclude a subdomain.

Example I want to match all subdomains on example.org except boon.example.org:

I've tried this:

$test = "boon.example.org";
$test2 = "null";
if(preg_match('#(?!boon)(\w+\.)?example\.org#', $test, $output)) {
    $test2 = $output[2] .'example.org';
}

But the output of test2 is: oon.example.org and not example.org

Somebody has an answer?


回答1:


If you're looking for only that exact subdomain, couldn't you just check if the string boon.example.org is present? Seems a bit overkill with regex for this.

Regardless, the following regex should do what you want:

.*(?<!\bboon\.|^.)example.org

Would return subdomain.example.org for all sub domains except boon.example.org or any sub domains of boon.example.org.




回答2:


This regex will works for you :

^(((?!boon).)+\.)?example\.org$

RegExr link




回答3:


Try This:

echo '<pre>';
$test = "boon.example.org";
$test2 = "null";
preg_match('/^(?!boon\.)([\w]+\.)?example\.org$/', $test, $output);
print_r($output);

This will match all sub-domain except boon.



来源:https://stackoverflow.com/questions/15245531/regex-exclude-a-subdomain-preg-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!