php.net has good reference material for parse_url, preg_match and general regular expressions. I’m trying to understand this snippet I found on SO here:
I’m familiar with all of the snippet excecpt this bit:
?P<domain>
What does this part do in relation to the whole. Particularly the ‘?P’. I’m assuming the <domain> just defines a key in the associative array returned.
function getDomain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))
{
return $regs['domain'];
}
return false;
}
The
?P<domain>part defines the name of that group. That means that you can then access it by name with$regs['domain']instead of by number as$regs[0]. It’s useful in large regexes since giving names to each of the groups makes it easier to understand what’s going on.