Damiano Barbati
Damiano Barbati

Reputation: 3496

PHP Regexp Non capturing group not working

I'm trying to get the domain and tld from an http_host by using the following regexp:

(?:^|\.)(.+?\.(?:it|com))

The regexp works correctly in gskinner.com.

Input:

domain.com
www.domain.com

Captured groups in both:

domain.com

However in php the following:

preg_match("/(?:^|\.)(.+?\.(?:it|com))/", "www.domain.com", $matches);
print_r($matches);

Output:

Array
(
    [0] => www.baloodealer.com
    [1] => www.baloodealer.com
)

What's wrong with this?

Upvotes: 0

Views: 114

Answers (2)

pobrelkey
pobrelkey

Reputation: 5973

I presume you want the last two parts of the domain? Before the TLD, don't match just any character:

"/(?:^|\.)([^\.]+?\.(?:it|com))$/"

(EDIT: anchoring to the end of the string, to fix bug pointed out in comment.)

Upvotes: 0

CrayonViolent
CrayonViolent

Reputation: 32532

You can do this:

preg_match("/[^.]+\.(?:it|com)$/", "www.domain.com", $matches);
print_r($matches);

/* output
Array
(
    [0] => domain.com
)
*/

Upvotes: 1

Related Questions