Home  >  Article  >  Backend Development  >  Universal Regular Expression for URL Matching with or without Protocols

Universal Regular Expression for URL Matching with or without Protocols

DDD
DDDOriginal
2024-10-22 08:47:30858browse

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+!*(),;?&amp=$_.-]+(:[a-z0-9+!*(),;?&amp=$_.-]+)?@)?([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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn