Home >Backend Development >PHP Tutorial >How to Match URLs with or Without Optional HTTP and WWW Prefixes Using a Regular Expression?
Matching URLs with Optional HTTP and WWW Prefixes
Regular expressions are powerful tools for complex pattern matching tasks. When it comes to matching URLs, there are often variations in the format, such as whether it includes "http://www." prefix or not.
Solution Using Regular Expression
To match URLs with or without the "http://www." prefix, the following regular expression can be used:
((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+$%_.-]*)?
Breakdown of the Expression:
Example Usage
To check if a given string matches the regular expression, use the following syntax:
<code class="php">if(preg_match(~^$regex$~i, 'www.example.com/etcetc', $m))</code>
This will return TRUE if the string matches the URL pattern with or without the "http://www." prefix.
The above is the detailed content of How to Match URLs with or Without Optional HTTP and WWW Prefixes Using a Regular Expression?. For more information, please follow other related articles on the PHP Chinese website!