简体   繁体   English

这个preg_replace_callback在PHP中做什么? 以及如何阻止它泄漏内存?

[英]what does this preg_replace_callback do in PHP? and how do I stop it leaking memory?

I've got a section of code on a b2evo PHP site that does the following: 我在b2evo PHP网站上有一段代码可以执行以下操作:

$content = preg_replace_callback(
    '/[\x80-\xff]/',
    create_function( '$j', 'return "&#".ord($j[0]).";";' ),
    $content);

What does this section of code do? 这部分代码做什么? My guess is that it strips out ascii characters between 128 and 256, but I can't be sure. 我的猜测是,它会去除128至256之间的ASCII字符,但我不确定。

Also, as it stands, every time this bit of code is called from within a page, PHP allocates and then does not free upto 2K of memory. 同样,就目前而言,每次从页面内调用此代码位时,PHP都会分配内存,然后不会释放多达2K的内存。 If the function is called 1000+ times on a page (this can happen), then the page uses an extra 2MB of memory. 如果该函数在页面上被调用1000次以上(可能发生),则该页面将使用额外的2MB内存。

This is causing problems with my web application. 这导致我的Web应用程序出现问题。 Why am I losing memory, and how do I rewrite this so I don't get a memory leak? 为什么我会丢失内存,以及如何重写它以免发生内存泄漏?

It's create_function that's leaking your memory - just use a normal function instead and you'll be fine. create_function泄漏了您的内存-只需使用常规函数即可,您会没事的。

The function itself is replacing the characters with numeric HTML entities ( &#xxx; ) 该函数本身正在用数字HTML实体( &#xxx; )替换字符&#xxx;

Not really stripping, it replaces high-Ascii characters by their entities. 并不是真正的剥离,而是通过其实体替换了高Ascii字符。

See preg_replace_callback . 请参阅preg_replace_callback
create_function is used to make an anonymous function, but you can use a plain function instead: create_function用于创建匿名函数,但您可以改用普通函数:

$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 do the job! [编辑]找到了一种更清洁,可能更快的方法来完成这项工作! ^_^ Just use htmlentities with options fitting your needs. ^ _ ^只需将htmlentities与适合您需求的选项一起使用。

It's a lot simpler to use preg_replace with the /e flag in your case: 在您的情况下,将preg_replace/e标志一起使用要简单得多:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM