Home >Backend Development >PHP Tutorial >Universal Regular Expression for URL Matching with or without Protocols
Regular Expression to Match URLs with or without Protocols
For URLs that may or may not include the "http://www" prefix, a regular expression can be used to perform the matching operation. A detailed RegEx pattern is provided below:
((https?|ftp)://)?([a-z0-9+!*(),;?&=$_.-]+(:[a-z0-9+!*(),;?&=$_.-]+)?@)?([a-z0-9\-\.]*)\.(([a-z]{2,4})|([0-9]{1,3}\.([0-9]{1,3})\.([0-9]{1,3})))(:[0-9]{2,5})?(/([a-z0-9+$_%-]\.?)+)*/?(\?[a-z+&$_.-][a-z0-9;:@&%=+/$_.-]*)?(\#[a-z_.-][a-z0-9+$%_.-]*)?
To utilize this pattern for URL validation, it can be applied in the following manner:
<code class="php">if (preg_match("~^$regex$~i", 'www.example.com/etcetc', $m)) var_dump($m); if (preg_match("~^$regex$~i", 'http://www.example.com/etcetc', $m)) var_dump($m);</code>
This RegEx solution offers a comprehensive way to match URLs regardless of whether they contain the "http://" prefix or not.
The above is the detailed content of Universal Regular Expression for URL Matching with or without Protocols. For more information, please follow other related articles on the PHP Chinese website!