Skip to content

Instantly share code, notes, and snippets.

@LouWii
Created October 1, 2015 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LouWii/0d4ddc384467511434c1 to your computer and use it in GitHub Desktop.
Save LouWii/0d4ddc384467511434c1 to your computer and use it in GitHub Desktop.
regex to handle different parts of a URL (host, path, query, anchor...)
<?php
$re = "/^(([^:\\/?#]+):)?(\\/\\/([^\\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
$str = "http://www.ics.uci.edu/pub/ietf/uri/?page=3&color=red#Related\n";
preg_match($re, $str, $matches);
/* matches will be
1. [0-5] `http:`
2. [0-4] `http`
3. [5-22] `//www.ics.uci.edu`
4. [7-22] `www.ics.uci.edu`
5. [22-36] `/pub/ietf/uri/`
6. [36-53] `?page=3&color=red`
7. [37-53] `page=3&color=red`
8. [53-61] `#Related`
9. [54-61] `Related`
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment