"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Universal Regular Expression for URL Matching with or without Protocols

Universal Regular Expression for URL Matching with or without Protocols

Published on 2024-11-08
Browse:164

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:

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);

This RegEx solution offers a comprehensive way to match URLs regardless of whether they contain the "http://" prefix or not.

Release Statement This article is reprinted at: 1729557977 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3