-->

preg_replace() [function.preg-replace]: Unknown mo

2019-03-06 08:34发布

问题:

in my website i want to replace links with some other link like this

www.abc.com or http://abc.com will be replaced with

http://www.XXXXXX.com/sonal?www.abc.com

or

http://www.XXXXXX.com/sonal?http://abc.com

so i am using this code but this code is giving some error

Warning: preg_replace() [function.preg-replace]: Unknown modifier '/' in /home/XXXXX/public_html/YYYYYYYYY/KKKKKK.php on line 495

$search_array = array(
   "/\[url]www|http://.([^'\"]*)\[\/url]/iU",
   "/\[url]([^'\"]*)\[\/url]/iU",
   "/\[url=www|http://.([^'\"\s]*)](.*)\[\/url]/iU",
   "/\[url=([^'\"\s]*)](.*)\[\/url]/iU"
);
$replace_array = array(
   "<a href=\"http://XXXXXX.com/sonal?.\\1\" target=\"_blank\" rel=\"nofollow\">www.   \\1</a>",
   "<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\1</a>",
   "<a href=\"http://XXXXXX.com/sonal?.\\1\" target=\"_blank\" rel=\"nofollow\">\\2</a>",
   "<a href=\"\\1\" target=\"_blank\" rel=\"nofollow\">\\2</a>"
);

$msg = preg_replace($search_array, $replace_array, $msg);
return $msg;

回答1:

There is few ways to solve that

Escaping "/"

$search_array = array(
  "/\[url]www|http:\/\/.([^'\"]*)\[\/url]/iU",
  "/\[url]([^'\"]*)\[\/url]/iU",
  "/\[url=www|http:\/\/.([^'\"\s]*)](.*)\[\/url]/iU",
  "/\[url=([^'\"\s]*)](.*)\[\/url]/iU"
);

Or using different regexp seperator like "#"

$search_array = array(
  "#\[url]www|http://.([^'\"]*)\[\/url]#iU",
  "#\[url]([^'\"]*)\[\/url]#iU",
  "#\[url=www|http://.([^'\"\s]*)](.*)\[\/url]#iU",
  "#\[url=([^'\"\s]*)](.*)\[\/url]#iU"
);


回答2:

"/\[url]www|http://.([^'\"]*)\[\/url]/iU",
 ^               ^^                  ^

You either need to escape the two // in the middle to \/\/, or, better, use different delimiters for the regex:

"~\[url]www|http://.([^'\"]*)\[/url]~iU",


标签: php regex bbcode