1

preg_replace 如何调用同一个类中的函数?

我尝试了以下方法:

<?php

defined('IN_SCRIPT') or exit;

class Templates {

    protected $db;

    function __construct(&$db) {
        $this->db = &$db;
        $settings = new Settings($this->db);
        $gamebase = new Gamebase($this->db);
        $this->theme = $settings->theme_id;
        $this->gameid = $gamebase->getId();
    }

    function get($template) {
        $query = $this->db->execute("
            SELECT `main_templates`.`content`
            FROM `main_templates`
            INNER JOIN `main_templates_group`
                ON `main_templates_group`.`id` = `main_templates`.`gid`
            INNER JOIN `main_themes`
                ON `main_themes`.`id` = `main_templates_group`.`tid`
            WHERE
                `main_themes`.`id` = '".$this->theme."'
            &&
                `main_templates`.`name` = '".$template."'
        ");
        while ($templates = mysql_fetch_array($query)) {
            $content = $templates['content'];

            // Outcomment
            $pattern[] = "/\/\*(.*?)\*\//is";
            $replace[] = "";

            // Call a template
            $pattern[] = "/\[template\](.*?)\[\/template\]/is";
            $replace[] = $this->get('header');

            $content = preg_replace($pattern, $replace, $content);
            return $content;
        }
    }
}

但这只是出现以下错误:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@site.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

一旦我对此发表评论:

// Call a template
$pattern[] = "/\[template\](.*?)\[\/template\]/is";
$replace[] = $this->get('header');

然后它工作。但我需要它来运行一个功能。

实际上我不需要它来运行带有header值的函数,我需要函数之间的[template]内容[/template]

有谁知道如何做到这一点?

4

1 回答 1

1

我认为您的脚本可能正在进入无限循环。如果你查看你的 get 函数,你正在调用它:

$replace[] = $this->get('header');

因此,在接听电话的过程中,您正在拉入标题。然后,这将执行完全相同的功能,该功能将自己拉入标题,一遍又一遍,一遍又一遍。您可能希望在何时$template为“标题”时禁用此行:

while ($templates = mysql_fetch_array($query)) {   

   $content = $templates['content'];

   // If this is the header, stop here
   if ($template == 'header') 
      return $content;

   // Rest of loop...
}

如果要执行正则表达式,请在 while 循环后添加:

if ($template == 'header') {
   $pattern = "/\[template\](.*?)\[\/template\]/is";
   $replace = 'WHATEVER YOU WANT TO REPLACE IT WITH';
   return preg_replace($pattern, $replace, $templates['content']);
}
于 2013-02-17T12:33:48.710 回答