Domanda

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))
È stato utile?

Soluzione

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

Altri suggerimenti

try this :-

$url = "https://james.wordpress.com/2013/05/13/my-product-final";
if (preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i",$url))
{
echo "Valid";
exit;
}

filter_var() function can also validate whether a string is URL or not

$website = "http://googl.com";

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
  {
  $websiteErr = "Invalid URL"; 
  }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top