php - error in use @preg_replace . What wrong in my code?
491
i write this code to replace $TheWhiteList to null string in message and show it to screen. but it not work. Can you tell me where I was wrong?
$TheWhiteList = Array
('http://facebook.com',
'google.com',
'facebook.com',
'stackoverflow.com',
);
$message ='test test tes tes [URL=http://facebook.com]http://facebook.com[/URL]
[URL=http://facebook.com]http://facebook.com[/URL]
[URL]http://stackoverflow.com[/URL]
[URL]http://facebook.com[/URL]
[URL]http://google.com[/URL]';
$string = '';
if(!empty($TheWhiteList))
{
foreach ($TheWhiteList as $value)
{
$string .= '|';
$string .=preg_quote($value);
}
$pattern = '#\[url=[\'\"]('.$string.')[\'\"]\].*\[\/url\]#imsU';
$replace = null;
$message = @preg_replace($pattern, $replace, $message);
}
print_r($message);
anyone please help me
Answer
Solution:
In your regex you require the URL to be surrounded by quotes but in the test input the URL comes unquoted after
URL=
. Hence no match is found and no replacement takes place.Answer
Solution:
I found two problems.
$string .= '|'; this adds an extra '|' at first. and '\" not marked as optional.
change
to
and pattern to