note 93824 modified in function.preg-match by danbrown

From: Date: Wed, 21 Oct 2009 16:23:42 +0000
Subject: note 93824 modified in function.preg-match by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161946@lists.php.net to get a copy of this message
As I wasted lots of time finding a REAL regex for URLs and resulted in building it on my own, I now have found one, that seems to work for all kinds of urls: <?php $regex = "((https?|ftp)\:\/\/)?"; // SCHEME $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP $regex .= "(\:[0-9]{2,5})?"; // Port $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor ?> Then, the correct way to check against the regex ist as follows: <?php if(preg_match("/^$regex$/", $url)) { return true; } ?> --was-- As I wasted lots of time finding a REAL regex for URLs and resulted in building it on my own, I now have found one, that seems to work for all kinds of urls: <?php $regex = "((https?|ftp)\:\/\/)?"; // SCHEME $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP $regex .= "(\:[0-9]{2,5})?"; // Port $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor ?> If someone discovers URLs that don't match, please let me know. Thank you! http://php.net/manual/en/function.preg-match.php

« previous php.notes (#161946) next »