2015-02-18 3 views
0

У меня возникли некоторые проблемы с заменой preg_replace с/е модификатора preg_replace_callback в этой функции:Проблемы с заменой/модификатором е к preg_replace_callback

private function parseFunctions() { 
    // replaces includes ({include file="..."}) 
    while(preg_match("/" .$this->leftDelimiterF ."include file=\"(.*)\.(.*)\"" 
         .$this->rightDelimiterF ."/isUe", $this->template)) 
    { 
     $this->template = preg_replace("/" .$this->leftDelimiterF ."include file=\"(.*)\.(.*)\"" 
             .$this->rightDelimiterF."/isUe", 
             "file_get_contents(\$this->templateDir.'\\1'.'.'.'\\2')", 
             $this->template); 
    } 


    // deletes comments from the template files 
    $this->template = preg_replace("/" .$this->leftDelimiterC ."(.*)" .$this->rightDelimiterC ."/isUe", 
            "", $this->template); 
    } 

Можете ли вы помочь мне с этим?

EDIT:

мне удалось зафиксировать второй, а другой

{ 
     $this->template = preg_replace_callback("/" .$this->leftDelimiterF ."include file=\"(.*)\.(.*)\"" 
             .$this->rightDelimiterF."/isU", 
             function(){$replacement="file_get_contents(\$this->templateDir.'\\1'.'.'.'\\2')"; 
             return $replacement;}, 
             $this->template); 
    } 

не работает. я получил следующее сообщение об ошибке:

file_get_contents ($ this-> templateDir '\ 1 '\ 2'.. ''.) file_get_contents ($ this-> templateDir '\ 1'.. '' . '\ 2') file_get_contents ($ this-> templateDir. '\ 1'. '.'. '\ 2') file_get_contents ($ this-> templateDir. '\ 1'. '.'. '\ 2') file_get_contents ($ this-> templateDir. '\ 1'. '.'. '\ 2') file_get_contents ($ this-> templateDir. '\ 1'. '.'. '\ 2')

I Я все еще относительно новичок в php, поэтому я не уверен, как справиться с этой проблемой.

+0

Я не понимаю, что вы делаете, почему вы заменить в то время, а затем внутри самого цикла. Просто одного из них должно быть достаточно. –

+0

Я тоже не уверен. Я не писал его изначально, мне нужно только иметь дело с ним. –

+0

Так вы могли бы хотя бы дать лучшее объяснение проблемы? –

ответ

0

Наконец-то я понял, что вы пытаетесь сделать. Функция обратного вызова должна получать массив всех совпадений или одного совпадения (в зависимости от того, что было найдено). Так это будет выглядеть примерно так: $this->template = preg_replace_callback("/" .$this->leftDelimiterF ."include file=\"(.*)\.(.*)\"".$this->rightDelimiterF."/isU", function($match){ $replacement="file_get_contents(\$this->match.'\\1'.'.'.'\\2')"; return $replacement;}, this->template); Если вам нужно какой-либо внешней переменной внутри анонимной функции, то объявить функцию обратного вызова function($match) use ($varname)

+0

Работает нормально, пока сайт не попытается загрузить файл шаблона. Затем я получаю сообщение об ошибке: file_get_contents ($ this-> match. '\ 1'. '.'. '\ 2') file_get_contents ($ this-> match. '\ 1'. '.'. '\ 2 ') file_get_contents ($ this-> match.' \ 1 '.'. '.' \ 2 ') file_get_contents ($ this-> match.' \ 1 '.'. '.' \ 2 ') file_get_contents ($ this-> match. '\ 1'. '.'. '\ 2') file_get_contents ($ this-> match. '\ 1'. '.'. '\ 2') –

+0

Что означает «загрузить шаблон» ? –

+0

Все материалы html включены в файлы .tpl. {include file = "assideleft.tpl"} {include file = "middlecontent.tpl"} {include file = "assideright.tpl"} Функция заменяет это содержимым файлов .tpl –

0

У вас есть 2 различных переменных $match и $matches. Вот рабочий код:

$this->template = preg_replace_callback(
    "/".$this->leftDelimiterF.'include file="([^"]+)"'.$this->rightDelimiterF."/isU", 
    function($match){ 
     $replacement = "file_get_contents(\$this->templateDir.$match[1])"; 
     return $replacement; 
    }, 
$this->template); 
+0

Я попробовал это, и, по крайней мере, у меня появилось совершенно новое сообщение об ошибке: Catchable fatal error: Object of class Closure не может быть преобразован в строку в C: \ xampp \ htdocs \ mxframework \ mxsframework \ data \ system \ classes \ view \ cl_template ,php on line 288 –

+0

Я добавил небольшое изменение: { $ this-> template = preg_replace_callback ( "/".$this->leftDelimiterF.'include file =" ([^ "] +)" '. $ this- .> rightDelimiterF "/ ГИП", функция ($ спичка) {$ замена = "file_get_contents (\ '$ this-> templateDir' $ матч [1].)"; возврат $ замена; }, $ это -> template); } error Сообщение сейчас: file_get_contents (\ 'templates/officelook2013/tplfiles /'. header.tpl) –

0
$this->template = preg_replace_callback("/" .$this->leftDelimiterF ."include file=\"(.*)\.(.*)\"" 
    .$this->rightDelimiterF."/isU", 
    function ($m) { return file_get_contents($this->templateDir.$m[1].'.'.$m[2]);}, 
    $this->template); 
+3

Можете ли вы предоставить краткое описание вашего кода? Спасибо! – Shawn

Смежные вопросы