PHP中是否有一种方法可以编译正则表达式,以便可以将其与多个字符串进行比较而不重复编译过程?其他主要语言可以做到这一点--Java、C#、Python、Javascript等。
preg正则表达式可以使用大写字母S(study)修饰符,这可能是您要查找的内容。
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
S
当一个模式将被多次使用时,值得花费更多时间进行分析,以加速匹配所需的时间。 如果设置了该修饰符,则执行此额外分析。 目前,研究模式仅对没有单个固定起始字符的非锚定模式有用。
Thread是指当前脚本正在运行的线程。在第一次使用后,编译好的正则表达式会被缓存,下次再使用时PHP不会再次编译它。
简单测试:
<?php
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
// test string
$text='The big brown <b>fox</b> jumped over a lazy <b>cat</b>';
$testTimes=10;
$avg=0;
for ($x=0; $x<$testTimes; $x++)
{
$start=microtime_float();
for ($i=0; $i<10000; $i++) {
preg_match_all('/<b>(.*)<\/b>0?/', $text, $m);
}
$end=microtime_float();
$avg += (float)$end-$start;
}
echo 'Regexp with caching avg '.($avg/$testTimes);
// regexp without caching
$avg=0;
for ($x=0; $x<$testTimes; $x++)
{
$start=microtime_float();
for ($i=0; $i<10000; $i++) {
$pattern='/<b>(.*)<\/b>'.$i.'?/';
preg_match_all($pattern, $text, $m);
}
$end=microtime_float();
$avg += (float)$end-$start;
}
echo '<br/>Regexp without caching avg '.($avg/$testTimes);
使用缓存的正则表达式平均速度为0.1秒,不使用缓存的正则表达式平均速度为0.8秒。
使用缓存可以使正则表达式的速度快8倍!
$i
不存在于模式中,并且它始终是该位置的0
。 - CSᵠ