PHP正则表达式这是获得此结果的最快方法吗?

时间:2013-09-24 11:03:51

标签: php regex string numbers

最后,我找到了解决方案,以获得我想要的东西。唯一的问题是 - 这是将帖子号码更改为链接帖子号码的最快捷方式吗?

BTW:我在这个帖子中征求意见:PHP Regular expression with arrows (>>)

也许有人会发现这个脚本很有用。

$string = "Lorem lipsum >>86721678 texttexttexttexttext >>64356 >234234 9894823 text  gdsfs>>54353<br /><br />";

    preg_match_all('!\>\>\d+!', $string, $matches);
    $nowy = array();
    //getting each number modified
    for ($i=0;$i<count($matches[0]);$i++)
    {
        $nowy[$i] = "<a href=''><font color='red'>".$matches[0][$i]."</font></a>";
    }

    echo str_replace($matches[0], $nowy, $string);

2 个答案:

答案 0 :(得分:0)

试试这个:

<?php
$string = "Lorem lipsum >>86721678 texttexttexttexttext >>64356 >234234 9894823 text  gdsfs>>54353<br /><br />";

$string = preg_replace_callback("#>>\d+#", "replacewithlinks", $string);
function replacewithlinks($matches)
{

  return "<a href=''><font color='red'>".$matches[0]."</font></a>";
}
echo $string;
?>

答案 1 :(得分:0)

快速测试,您的方法在我的计算机上平均使用5.50746917725E-5秒。

由于简单性和易读性,我对此进行了测试:

echo preg_replace('!\>\>\d+!', "<a href=''><font color='red'>$0</font></a>", $string);

它耗尽3.00407409668E-5秒,所以几乎是速度的两倍。


备注:您不应该专注于此类操作的性能,除非您要经历非常大的数据块。如果它不是人类明显的话,那就好了。

在这种情况下,您应该专注于可读性和逻辑,如果您将来需要保留和修改此代码是多么容易,至少这是我的意见

此外,如果你想要更好的性能测试,请用for循环包装,循环10000次或你认为合适的任何东西,例如使用microtime()和/或memory_get_usage()