如何以最快的方式删除空格和l值


How can I remove spaces and l values at the fastest way?

我写了一个缓存类。它在多次数据库查询后自动获取页面内容,并将其另存为.html文件。每隔 600 秒,它就会从此.html页面读取,而不是查询。

为了更快地提高阅读速度,我想删除不需要的字符,如" "(空格('''l 等。我该怎么做?

我知道我可以通过多种方式做到这一点。 修剪、str_replace等等。我想知道最快 - 也是最安全(所以它不会破坏javascript(的方式来依赖。:)

谢谢。

我给你的建议是:不要

除非您的模板制作得太差,以至于它们生成的标记主要由空格组成。

您需要一种简单、快速且安全的空间删除方法。但实际上,您只能选择这三个属性中的两个。

  • 如果你想要简单和快速:使用str_replace,但它破坏了你的javascript。
  • 如果您想要简单和安全:自己编辑文件并手动删除空格。
  • 如果你想要快速和安全:你必须使用一些复杂的解析器和/或优化工具。

这取决于你!

首先要注意你的javascript代码,如果你有javascript注释,它可能会破坏你的javascript代码。

先看看 Yui 压缩器和/或 Google Closure Compressor 来优化你的 JavaScript。

对于页面的其余部分,您可以在那些方便的函数中传递它

使用简单的PHP代码压缩HTML,CSS和Javascript

希望对你有帮助

我想

使用str_replace是最快的方法!另一种选择是preg_replace,但正则表达式不如简单的字符串替换快。

前段时间我写了这个方法,整理一些源代码:

private function makeTiny($source, $type) {
    // Get replacements
    $replacements = array();
    if ($this->conf[$type]['stripTabs']) {
        $replacements[] = "'t";
    }
    if ($this->conf[$type]['stripNewLines']) {
        $replacements[] = "'n";
        $replacements[] = "'r";
    }
    // Do replacements
    $source = str_replace($replacements, '', $source);
    // Strip comments
    if ($this->conf[$type]['stripComments']) {
        $source = preg_replace('/<'!'-'-.*?'-'->/is', '', $source);
    }
    // Strip double spaces
    if ($this->conf[$type]['stripDoubleSpaces']) {
        $source = preg_replace('/( {2,})/is', ' ', $source);
    }
    if ($this->conf[$type]['stripTwoLinesToOne']) {
        $source = preg_replace('/('n{2,})/is', "'n", $source);
    }
    return $source;
}

据我所知,这并不是杀死内联JavaScript!但是您应该先尝试一下。

尝试

$newcontent = preg_replace('/('n|'s|'t)+/','',$oldcontent);

这将替换空格和制表符以及新行