Preg_replace调用函数在同一个类中?

时间:2013-02-17 12:15:12

标签: php function object preg-replace

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]之间的内容在函数中。

有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分: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']);
}