What does this preg_replace_callback do in PHP? and how can i stop it leaking memory?
I have a section of code on the PHP b2evo site that does the following:
$content = preg_replace_callback(
'/[\x80-\xff]/',
create_function( '$j', 'return "&#".ord($j[0]).";";' ),
$content);
What does this section of code do? I am guessing it is removing ascii characters between 128 and 256, but I cannot be sure.
Also, every time this bit of code is called from within the page, PHP allocates and doesn't free up to 2K of memory. If the function is called 1000+ times on the page (this can happen), then the extra memory of 2MB is used on the page.
This is causing problems with my web app. Why am I losing memory, and how do I rewrite this so that I don't lose memory?
source to share
Not completely stripping it out, it replaces the high-level Ascii characters with its entities.
See preg_replace_callback .
create_function is used to create an anonymous function, but you can use a regular function instead:
$content = 'Çà ! Nœm dé fîçhïèr tôrdù, @ pöür têstër... ? ~ Œ[€]';
$content = preg_replace_callback('/[\x80-\xff]/', 'CB_CharToEntity', $content);
echo $econtent . '<br>';
echo htmlspecialchars($content) . '<br>';
echo htmlentities($content) . '<br>';
echo htmlentities($content, ENT_NOQUOTES, 'cp1252') . '<br>';
function CB_CharToEntity($matches)
{
return '&#' . ord($matches[0]) . ';';
}
[EDIT] Found a cleaner, probably faster way to get the job done! ^ _ ^ Just use htmlentities with options that suit your needs.
source to share