note 23350 deleted from function.preg-match by sniper

From: Date: Tue, 30 Sep 2003 12:12:31 +0000
Subject: note 23350 deleted from function.preg-match by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57391@lists.php.net to get a copy of this message
Note Submitter: http://www.ravis.org/ ---- Here's an expression that breaks apart any standard URI/URL into all it's various components (including username/password and query string)... preg_match("/^((.*?):\/\/)?(([^:]*):([^@]*)@)?([^\/:]*) (:([^\/]*))?([^\?]*\/?)?(\?(.*))?$/",$URI,$Components); list(,,$Protocol,,$Username,$Password,$Host,,$Port,$Path,,$Query) = $Components; Breakdown: expected format is in 'single quotes' examples (eg:) are examples of what would be returned by the above expression ^ Start of line ((.*?):\/\/)? Possibly a protocol ('protocol://' - eg: "http") (([^:]*):([^@]*)@)? Possibly a username password combo ('username:password@' - eg: "jsmith" and "birthday") ([^\/:]*) A host or IP ('host:' or 'host/' - eg: "your.server.com") (:([^\/]*))? Possibly a port (':port/' - eg: "80") ([^\?]*\/?)? Possibly a path, possibly with a trailing slash ('/path/to/file' or '/path/to/dir/' - eg "/path/to/file.zip") (\?(.*))? Possibly a query string ('?query' - eg: "var1=val&var2=val") $ End of line So we have: (optionals are in {braces}) {protocol://}{username:password@}host{:port}{/path}{?query} No checks are done for "proper" formatting (eg: ports are digits only). You can implement your own checks if you like. I prefer to break apart the URI first and don't worry about what's there (at least at this stage). Also be careful with $Protocol, as it could be mixed case (http, HTTP, or hTtP) - you should do something like a strtolower() on it before working with it. Naturally make sure the entire preg_match expression is on one line (and not split like shown here).

« previous php.notes (#57391) next »