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

914

Answer

Solution:

In your regex you require the URL to be surrounded by quotes but in the test input the URL comes unquoted afterURL=. Hence no match is found and no replacement takes place.

900

Answer

Solution:

I found two problems.

$string .= '|'; this adds an extra '|' at first. and '\" not marked as optional.

change

$string .= '|';

to

if( $string ) {
   $string .= '|';
}

and pattern to

$pattern = '#\[url=[\'\"]?('.$string.')[\'\"]?\].*\[\/url\]#imsU'

People are also looking for solutions to the problem: javascript - Getting error that Element doesn't exist (PHP->JS) when trying to remove div

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.