Thomas Clowes
Thomas Clowes

Reputation: 4609

PHP Regular Expression NOT starting with.. negative lookbehind not working?

I am trying to extract a nameserver. The format of $output is such that it contains ns1.nameserver.com for example.

It might also contain www.apple.com.
This is not a nameserver of course.

I am trying to not include any results therefore which contain www.
My attempt is below:

$regexp = "/(?<!www)([A-Za-z0-9-]+[\.][A-Za-z0-9-]+[\.][A-Za-z0-9-\.]+)/i";
preg_match_all($regexp, $output, $nameservers);

Upvotes: 0

Views: 2033

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336408

You need lookahead, not lookbehind:

/(?!www)([A-Za-z0-9-]+[\.][A-Za-z0-9-]+[\.][A-Za-z0-9-\.]+)/i

However, this is probably not enough because it will then proceed to match abc.def.com in the string www.abc.def.com. You'd also need some anchors and a lookbehind (and you don't need some brackets, backslashes nor the i modifier):

/(?<!\.)(?!www)\b([A-Za-z0-9-]+\.[A-Za-z0-9-]+\.[A-Za-z0-9.-]+)/

Upvotes: 3

Related Questions