Reputation: 18798
I must admit I've never gotten used to using regex, however recently I ran into a problem where the work around would've been more of a pain than using regex. I need to be able to match anything that follows the following pattern at the beginning of a string:
{any_url_safe_word}
+( "/http://"
|| "/https://"
|| "www."
) + {any word}
.
So the following should match:
cars/http://google.com#test
cars/https://google.com#test
cars/www.google.com#test
The follwing shouldn't match:
cars/httdp://google.com#test
cars/http:/google.com#test
What I tried so far is: ^[\w]{1,500}\/[(http\:\/\/)|(https:\/\/])|([www\.])]{0,50}
, but that matches cars/http
from cars/httpd://google.com
.
Upvotes: 2
Views: 965
Reputation: 4953
This regex could do:
^[\w\d]+\/(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}
And if you want to get everything that comes after it, you can just add (.*)
to the end...
And since it seems that the more or less general list of URL safe words contains ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=
Source
, you may include that too, so you'll get (after simplification):
^[!#$&-.0-;=?-\[\]_a-z~]+\/(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}
Upvotes: 3
Reputation: 23749
<?php
$words = array(
'cars/http://google.com#test',
'cars/https://google.com#test',
'cars/www.google.com#test',
'cars/httdp://google.com#test',
'cars/http:/google.com#test',
'c a r s/http:/google.com#test'
);
foreach($words as $value)
{
/*
\S+ - at least one non-space symbol
\/ - slash
(https?:\/\/) - http with possible s then ://
| - or
(www\.) - www.
.+ - at least one symbol
*/
if (preg_match('/^\S+\/(https?:\/\/)|(www\.).+/', $value))
{
print $value. " good\n";
}
else
{
print $value. " bad\n";
}
}
Prints:
cars/http://google.com#test good
cars/https://google.com#test good
cars/www.google.com#test good
cars/httdp://google.com#test bad
cars/http:/google.com#test bad
c a r s/http:/google.com#test bad
Upvotes: 0
Reputation: 1237
Check out the demo.
[a-z0-9-_.~]+/(https?://|www\.)[a-z0-9]+\.[a-z]{2,6}([/?#a-z0-9-_.~])*
Edit: taken @CD001 comment into account. Be sure to use the i
modifier if you don't mind case-sensitivity.
Upvotes: 0