Skip to content

Instantly share code, notes, and snippets.

@nyamsprod
Last active November 7, 2015 13:49
RegularExpressionDocumented.php
<?php
$uri = 'http://www.ics.uci.edu/pub/ietf/uri/#Related';
$regexp = ',^
((?<scheme>[^:/?\#]+):)? # URI scheme component
(?<authority>//([^/?\#]*))? # URI authority part
(?<path>[^?\#]*) # URI path component
(?<query>\?([^\#]*))? # URI query component
(?<fragment>\#(.*))? # URI fragment component
,x';
preg_match($regexp, $uri, $matches);
var_dump($matches);
// array(15) {
// [0]=> string(44) "http://www.ics.uci.edu/pub/ietf/uri/#Related"
// [1]=> string(5) "http:"
// ["scheme"]=> string(4) "http"
// [2]=> string(4) "http"
// ["authority"]=> string(17) "//www.ics.uci.edu"
// [3]=> string(17) "//www.ics.uci.edu"
// [4]=> string(15) "www.ics.uci.edu"
// ["path"]=> string(14) "/pub/ietf/uri/"
// [5]=> string(14) "/pub/ietf/uri/"
// ["query"]=> string(0) ""
// [6]=> string(0) ""
// [7]=> string(0) ""
// ["fragment"]=> string(8) "#Related"
// [8]=> string(8) "#Related"
// [9]=> string(7) "Related"
// }
<?php
$uri = 'http://www.ics.uci.edu/pub/ietf/uri/#Related';
$regexp = ',^((?<scheme>[^:/?\#]+):)?(?<authority>//([^/?\#]*))?(?<path>[^?\#]*)(?<query>\?([^\#]*))?(?<fragment>\#(.*))?,';
preg_match($regexp, $uri, $matches);
var_dump($matches);
// array(15) {
// [0]=> string(44) "http://www.ics.uci.edu/pub/ietf/uri/#Related"
// [1]=> string(5) "http:"
// ["scheme"]=> string(4) "http"
// [2]=> string(4) "http"
// ["authority"]=> string(17) "//www.ics.uci.edu"
// [3]=> string(17) "//www.ics.uci.edu"
// [4]=> string(15) "www.ics.uci.edu"
// ["path"]=> string(14) "/pub/ietf/uri/"
// [5]=> string(14) "/pub/ietf/uri/"
// ["query"]=> string(0) ""
// [6]=> string(0) ""
// [7]=> string(0) ""
// ["fragment"]=> string(8) "#Related"
// [8]=> string(8) "#Related"
// [9]=> string(7) "Related"
// }
<?php
$uri = 'http://www.ics.uci.edu/pub/ietf/uri/#Related';
$regexp = ',^(([^:/?\#]+):)?(//([^/?\#]*))?([^?\#]*)(\?([^\#]*))?(\#(.*))?,';
preg_match($regexp, $uri, $matches);
var_dump($matches);
// array(10) {
// [0]=> string(44) "http://www.ics.uci.edu/pub/ietf/uri/#Related"
// [1]=> string(5) "http:"
// [2]=> string(4) "http"
// [3]=> string(17) "//www.ics.uci.edu"
// [4]=> string(15) "www.ics.uci.edu"
// [5]=> string(14) "/pub/ietf/uri/"
// [6]=> string(0) ""
// [7]=> string(0) ""
// [8]=> string(8) "#Related"
// [9]=> string(7) "Related"
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment