Universal Regular Expression for URL Matching with or without Protocols

DDD
Release: 2024-10-22 08:47:30
Original
857 people have browsed it

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+$%_.-]*)?
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!