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:
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.
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