preg_replace_callback

Hi Guys!

I am using the following code to remove <br /> tags from a string of user entered text. Basically the code below should remove any <br /> tags added within <ol></ol> tags (if that makes sense).

Unfortunately, it doesn’t work correctly and I get the following error:

Warning: htmlentities() expects parameter 1 to be string, array given in /home/user/public_html/classes/main.class.php on line 1212

Any ideas?


$result = nl2br($result);
$result = preg_replace_callback('/<ol>(.*)<\\/ol>/is', array('self', 'RestoreOl'), $result);

function RestoreOl($text)
	{
    	$text = str_replace(array("<br />\\r\
", "<br />\\r", "<br />\
"), "\
", $text);
    	return '<ol>' . htmlentities($text) . '</ol>';
	}

Try replacing the second argument of str_replace with this:


array("\
", "\
", "n")

This will be your final code:


$result = nl2br($result);
$result = preg_replace_callback('/<ol>(.*)<\\/ol>/is', array('self', 'RestoreOl'), $result);

function RestoreOl($text)
    {
        $text = str_replace(array("<br />\\r\
", "<br />\\r", "<br />\
"), array("\
", "\
", "n"), $text);
        return '<ol>' . htmlentities($text) . '</ol>';
    }  

The error isn’t been cause because of the str_replace function but because a regular expression returns an array and NOT a string, in your callback function add

echo '<pre>';
print_r($text);
echo '</pre>';

which will output the array allowing you to see which index you need to target within it.