Reputation: 8424
I need to make a regular expression for php preg_match that does the following matching.
This is the function
function isValidURL($url,$searchfor){
return preg_match("/\b.$searchfor \b/i", $url);
}
I need to find the somedomain.com in the following Possible Strings entering the function
http://www.somedomain.com http://somedomain.com http://www.somedomain.com/anything http://somedomain.com/anything http://anything/somedomain.com
So I need a regular expression that does this
http://www.somedomain.com Will Match http://somedomain.com Will Match http://www.somedomain.com/anything Will Match http://somedomain.com/anything Will Match
but
http://anything/somedomain.com Will NOT match
Upvotes: 0
Views: 1965
Reputation:
What about using parse_url()
?
if( strpos(parse_url($url, PHP_URL_HOST), 'somedomain.com') !== false )
{
// hostname contains 'somedomain.com'.
}
Upvotes: 3
Reputation: 145472
All this requires is a placeholder for the URL beginning. Excluding slashes with a negated character class [^/]
might already be sufficient:
function isValidURL($url,$searchfor){
return preg_match("~http://[^/\s]*\.$searchfor(/|$|\s)~i", $url);
}
Note that this fails some edge cases, like user:pw@
pairs. And no idea if your $searchfor
was supposed to contain the TLD already. Also don't forget to preg_quote
it.
Upvotes: 1
Reputation: 4182
Try this...
$url = "http://komunitasweb.com/";
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):? (d+)?/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}
Copied from a google searh on "php url regular expression". Check google out, awesome tool. :-)
Upvotes: 2