views:

26

answers:

1

I tried to directly convert an "eregi" expression to a "preg_match" expression.

$ACCEPT_CHARS = "a-z0-9_~#&;=./?+-";
$msg = preg_match("/ (http|https|ftp|gopher|news)://([$ACCEPT_CHARS]+)/i", "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>", $msg);

However, I get:

Warning: preg_match() [function.preg-match]: Unknown modifier '&' in /var/www/comm.borealisbbi.org/includes/functions_parse.php on line 282

What have I done wrong?

The original line was:

 $msg = eregi(" (http|https|ftp|gopher|news)://([$ACCEPT_CHARS]+)", "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>", $msg);
+2  A: 

That's because of the forward slashes in your regex /. Since you used them as delimiters, the regex engine expects the expression to be over after the /. You can escape it, or use a different delimiter:

$msg = preg_replace("~ (http|https|ftp|gopher|news)://([$ACCEPT_CHARS]+)~i", "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>", $msg);

That said...

  • I don't understand why you are using preg_match() here. I think you meant preg_replace() ?

  • Your regex is not very robust. If you are validating the URL, you could user filter_var() instead:

    filter_var('example.com', FILTER_VALIDATE_URL);
    
NullUserException