Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 提高正则表达式的速度并使用preg_替换段塞_Php_Regex_Slug - Fatal编程技术网

Php 提高正则表达式的速度并使用preg_替换段塞

Php 提高正则表达式的速度并使用preg_替换段塞,php,regex,slug,Php,Regex,Slug,以前我一直在回显$obj->html,但当前的项目要求检查html是否有类似{whatever}的段塞,并用其他内容替换它们 我有两个问题。首先,这段代码比我想要的要慢: class Foo { function draw_content() { $slug = "/(?<=\{).*(?=\})/"; if (preg_match($slug, $this->html, $matches)) { foreach ($matches as $ma

以前我一直在回显$obj->html,但当前的项目要求检查html是否有类似
{whatever}
的段塞,并用其他内容替换它们

我有两个问题。首先,这段代码比我想要的要慢:

class Foo {

  function draw_content() {
    $slug = "/(?<=\{).*(?=\})/";
    if (preg_match($slug, $this->html, $matches)) {
        foreach ($matches as $match) {
            if (method_exists($this,$match))    {
                $replacement = $this->$match();
                $this->html = preg_replace("/\{$match\}/", $replacement, $this->html);
            }
        }
    } 
    return $this->html;
 } // fn

  function new_releases() {
    echo "new release book covers"; 
  }  // fn

} // class
class-Foo{
函数draw_content(){

$slug=“/(?您可以通过以下方式替换您的模式:

$slug = '~{\K[^}]*+(?=})~';
首先,你应该用一个
preg\u replace\u回调函数来替换你的
preg\u match
测试和你的
preg\u replace
,试试这样的方法(并纠正错误:)


您可以通过以下方式替换您的模式:

$slug = '~{\K[^}]*+(?=})~';
首先,你应该用一个
preg\u replace\u回调函数来替换你的
preg\u match
测试和你的
preg\u replace
,试试这样的方法(并纠正错误:)


哇,太快了!谢谢!对这种奇怪的preg\u replace()行为有什么看法吗?你太棒了!!我在
preg\u replace\u callback()上挠头
docs。这绝对解决了我的问题!@jerrygarciuh:真为你高兴。所以我还有一个问题-服务器正在运行PHP5.3.13;文档说$this在anon funcs中不可用,直到5.4我才可以用命名的func替换它?我试着制作一个全局并将$this克隆到其中,但没有骰子;不适用于anon func。现在我欠你很多纽约啤酒!你大大改善了我的一天!哇,真是快多了!谢谢!对这种奇怪的preg\u replace()行为有什么看法吗?你太棒了!!我在
preg\u replace\u callback()上挠头
docs。这绝对解决了我的问题!@jerrygarciuh:真为你高兴。所以我还有一个问题-服务器正在运行PHP5.3.13;文档说$this在anon funcs中不可用,直到5.4我才可以用命名的func替换它?我试着制作一个全局并将$this克隆到其中,但没有骰子;不适用于anon func。现在我欠你很多纽约啤酒!你大大改善了我的一天!
$slug = '~{\K[^}]*+(?=})~';
function draw_content() {
    $slug = '~{([^}]*+)}~';
    $that = $this;
    $this->html = preg_replace_callback( $slug, function ($m) use ($that) {
        if (method_exists($that, $m[1]))
            return $that->$m[1]();
        return $m[0]; }, $this->html);
    return $this->html;
}