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?

0


source to share


3 answers


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.

+3


source


It create_function

's that memory leak - just use a regular function and you should be fine.



The function itself replaces characters with numeric HTML objects ( &#xxx;

)

+4


source


In your case, it's much easier to use preg_replace

with a flag /e

:

$content = preg_replace(
    '/[\x80-\xff]/e',
    '"&#".ord($0).";"',
    $content);

      

0


source







All Articles