- preg_match: documentation ( source)
<?php
$expr = '!
^
(?:
(?P<scheme> [a-z][a-z0-9.]* )
:
)?
(?:
//
(?<authority>
(?:
(?P<user> [^:@]+ )
(?:
:
(?P<pass> [^@]+ )
)?
@
)?
(?P<host> [^:/]+ )
(?:
:
(?P<port> [0-9]+ )
)?
)
)?
(?:
/
(?P<path> /[^?#]+ )
)?
(?:
\?
(?P<query> [^#]+ )
)?
(?:
#
(?P<fragment> .+ )
)?
$
!ix';
$urls = [
'http://host.com/path',
'http://user@host.com/path',
'http://user:pass@host.com/path',
'http://user:pass@host.com:8080/path',
'//user:pass@host.com:8080/path',
'http://user:pass@host.com:8080/path?query#fragment',
];
foreach ($urls as $str) {
echo "$str\n";
preg_match($expr, $str, $matches);
foreach ($matches as $key => $match) {
if (!is_int($key) && $match !== '') {
echo "$key: $match\n";
}
}
echo "\n";
}