【问题标题】:Is there a faster alternative to preg functions and regex [closed]是否有比 preg 函数和正则表达式更快的替代方法 [关闭]
【发布时间】:2015-05-07 16:02:49
【问题描述】:

我正在寻找一种更好的方式来为我的网络代理编写插件。它涉及解析用户想要的页面的 html,去除除非东西(广告、烦人的 js 等...)并将页面提供给用户。

除非东西部分是使用preg_replace and regex完成的。是的,我知道DOMDocument比正则表达式更推荐,但preg_replace is faster性能是最重要的,因为我需要尽快为用户服务,释放系统资源。

这里是一个典型的 preg_replace 语句示例

$input = preg_replace('#<div id="above-related".*?</div>#s', '', $input); 在一个典型的插件中可能有 4-15 个 preg_replace 语句。

我可以优化 strip out unless stuff 部分

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    您可以通过减少正则表达式的数量、表达式的复杂性和输入大小来加快匹配速度。

    例如你的例子:'#<div id="above-related".*?</div>#s'

    您可以使用strpossubstr 来减小输入的大小:

    $input = "<html>..</html>";
    $offset = 0;
    while ($start = strpos('<div id="above-related"', $input, $offset)) {
        $end = strpos("</div>", $input, $start);
        $substr = substr($input, $start, $end); // take the small slice
        $result = preg_replace('#<div id="above-related".*?</div>#s', '', $substr);
        // stitch the input back together:
        $input = substr($input, 0, $start) . $result . substr($input, $end);
        $offset = $start + 1; // continue looking for more matches
    }
    

    在您的示例中,替换实际上并没有使用匹配,因此它可以是直接向上的:

    $input = "<html>..</html>";
    $offset = 0;
    $match_start = '<div id="above-related"';
    $match_end = '</div>';
    while ($start = strpos($match_start, $input, $offset)) {
        $end = strpos($match_end, $input, $start);
        $input = substr($input, 0, $start + strlen($match_start)) . substr($input, $end);
        $offset = $start + 1; // continue looking for more matches
    }
    

    这里的诀窍是 strpossubstrpreg_replace 快得多(轻松 100 倍)。

    如果您可以找到非正则表达式匹配,或者甚至可以为每个规则找到非正则表达式替换策略,那么您将看到显着的加速。

    【讨论】:

      猜你喜欢
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多