我正在寻找一种更好的方法来为我的Web代理编码插件。它涉及解析用户想要的页面的html,除非用户脱掉,否则除非有东西(广告,烦人的JS等),否则请脱掉。..)并将页面发送给用户。
脱掉,除非零件是使用 preg_replace and regex
完成的。是的,我知道我知道DOMDocument
建议通过REGEX使用preg_replace更快。尽快免费进行系统资源。
这是典型的Preg_replace语句
的示例 $input = preg_replace('#<div id="above-related".*?</div>#s', '', $input);
在一个典型的插件中,可能有4-15个preg_replace语句。
除非东西 part
您可以通过减少具有正则表达式的数量,表达式的复杂性和输入大小来加快匹配。
例如,您的示例: '#<div id="above-related".*?</div>#s'
您可以使用strpos
和substr
减少输入的大小:
$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
}
这里的诀窍是strpos
和substr
比preg_replace
(易于100x)快得多。
如果您可以找到非规范的表达匹配,甚至可以找到每个规则的非规范表达替换策略,那么您将看到明显的速度。