Search code examples
phppreg-matcheregi

URL validation using eregi() but now with preg_match


eregi() is deprecated and need to replace with preg_match. How can I convert following syntax into preg_match? Suppose following are url and it's required regex pattern:

$url = "https://james.wordpress.com/2013/05/13/my-product-final";
$urlregex = "^(https?|ftp)\:\/\/([a-zåäöÅÄÖæÆøØ0-9+!*(),;?&=\$_.-]+(\:[a-zåäöÅÄÖæÆøØ0-9+!*(),;?&=\$_.-]+)?@)?[a-zåäöÅÄÖæÆøØ0-9+\$_-]+(\.[a-zåäöÅÄÖæÆøØ0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-zåäöÅÄÖæÆøØ0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-zåäöÅÄÖæÆøØ0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-zåäöÅÄÖæÆøØ0-9+\$_.-]*)?\$";

Following code works fine:

if (eregi($urlregex, $url)) {
echo "Valid";
exit;
}

I tried to convert into 'preg_match' but it couldn't work:

if (preg_match("#$urlregex#i", $url)) {
echo "Valid";
exit;
}

Also tried like this:

if (preg_match('/'.$urlregex.'/i', $url))

Solution

  • It doesn't work because the char you're using as delimiter (ie. #) is present in the regex.

    You can:

    • escape the # in the regex: \#
    • change the delimiter to a char that is not present in the regex