3

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))
Jerry3456
  • 79
  • 7

3 Answers3

1

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
Toto
  • 89,455
  • 62
  • 89
  • 125
0

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

Rajeev Ranjan
  • 4,152
  • 3
  • 28
  • 41
0
$website = "http://googl.com";

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
  {
  $websiteErr = "Invalid URL"; 
  }
Youssef Subehi
  • 2,790
  • 1
  • 18
  • 20