1

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?

1
  • Do you really need to use regex? Commented Jan 4, 2011 at 9:36

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

1

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)
        );
    }
?>

Comments

0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.