开发者

php regex does domain string have www and top level domain

I'm abit of an amateur when it comes to regex but consider i have the following three domains

www.google.com
www.google.co.uk
google.com

I would like to create some开发者_开发问答 regex that will test to see if the domain has a www and also a .co.uk or .com

Does anybody know of some regex that will test for this?


You don't need regex for this , you can use strpos witch is sayd to be faster than regex .

if ( strpos('www.', $mystring) !== false ) {
    //www was found in the string
} else {
    //www was not foun in the string
}

If you realy whant to be slower and use regex you can test for all of them like this

preg_match('/www|\.com|\.co\.uk/', $mystring);

If for example you whant to apply different logic for www than for .com you can use

preg_match('/www/', $string);
preg_match('/\.com/', $string);
preg_match('/\.co\.uk/', $string);


Try this:

/^www.*(?:com|co\.uk)$/


From what I understand from your question, the domain needs to start with www AND ends with either .co.uk OR .com. So here is the RegExp:

<?php
    $domains = array(
        "www.google.com",
        "www.google.co.uk",
        "google.com"
    );
    foreach($domains as $domain){
        echo sprintf(
            "%20s -> %d\n",
            $domain,
            preg_match("@^www\\..+(\\.co\\.uk|\\.com)$@", $domain)
        );
    }
?>


Simple

$ar = array();
$t = array("www.google.com","www.google.co.uk","google.com","www.google");
foreach ($t as $str) {
    if (preg_match('/^www\.(.*)(\.co.uk|\.com)$/',$str)) {
        echo "Matches\n";
    }
}

Conditional

$ar = array();
$t = array("www.google.com","www.google.co.uk","google.com","www.google");
foreach ($t as $str) {
    switch (true) {
        case preg_match('/^www\.(.*)$/',$str) :
        // code
        case preg_match('/^(.*)(\.co.uk)$/',$str) :
        // code
        case preg_match('/^(.*)(\.com)$/',$str) :
        // code
        break;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜