Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Sprawdzanie w szablonach (<if></if>)
Forum PHP.pl > Forum > PHP
gulldarek
Mam taka funkcje:

[php:1:29914852a5]<?php
function gettemplate($templatename, $gethtmlcomments = 1)
{
if(file_exists("templates/$templatename.htm")){

$fd = fopen ("templates/$templatename.htm", "r");

$template_file = fread ($fd, filesize ("templates/$templatename.htm"));
$template = preg_replace_callback('/{_([^ ]+)}/U', create_function('$matchs', 'return $GLOBALS["lang_$matchs[1]"];'), $template_file);

$template = preg_replace_callback('/{([^ ]+)}/U', create_function('$matches', 'return $GLOBALS[$matches[1]];'), $template);

if ($options['addtemplatename'] = 1 AND $gethtmlcomments = 1)
{
$template = "n<!-- POCZATEK SZABLONU: $templatename -->n$templaten<!-- KONIEC SZABLONU: $templatename -->n";
}

fclose($fd);

return $template;

} else {

return "<center><font color="red">Wystapil blad krytyczny - Brak szablonu '$tplfile'. Skontaktuj sie z administratorem.</font></center>";

}

}

?>[/php:1:29914852a5]

Chce miec mozliwosc dodania do szablonu czegos takiego:

Kod
<if condition="$show"> tutaj tresc strony </if>


i jesli funkcja natrafi na taki kod zeby sprawdzila czy np. $show == 1, a jesli tak to wyswietlila kod miedzy znacznikiem <if></if>.

Ma ktos pomysl jak to zrobic?

sad.gif widze, ze chyba nikt sad.gif
gulldarek
Sorry za double posta ale ten temat chyba za duzo spadl.

Pomoze ktos?
scanner
Musiałbyś sprawdzac tempklate pod względem istanienia pary <if></if> a następnie parsować to co jest wewnątrz <if>. Jest z tym trochę roboty.
gulldarek
cos takiego?

[php:1:5015775afd]<?php
$if_lookfor = '<if condition=';
$if_location = -1;
$if_end_lookfor = '</if>';
$if_end_location = -1;

$if_location = strpos($template, $if_lookfor, $if_end_location + 1);
if ($if_location === false)
{
break;
}

$zmienna_start = $if_location + strlen($if_lookfor) + 2;
$delimiter = $template[$zmienna_start - 1];

if ($delimiter != '"' AND $delimiter != ''')
{
$if_end_location = $if_location + 1;
continue;
}
$if_end_location = strpos($template, $if_end_lookfor, $zmienna_end + 3);

if ($if_end_location === false)
{
return str_replace("'", ''', $template); }

for ($i = $zmienna_start; $i < $strlen; $i++)
{
if ($template["$i"] == $delimiter AND $template[$i - 2] != '' AND $template[$i + 1] == '>')
{
$zmienna_end = $i - 1;
break;
}
}
$zmienna = substr($template, $zmienna_start, $zmienna_end-$zmienna_start);

?>[/php:1:5015775afd]
scanner
nie mam mołżiwości chwilowo sprawdzić, bo mi phpJuice nie działa, ale pobieżnie przeglądając powinno to działać. Czy w wyniku dostajesz okrteślony warunek?

BTW: może przyjrzyj się kodowi Smarty?[/code]
BzikOS
Hmm czy ja czegoś nie zrozumiałem, czy Wy cos mieszacie? Nie wystarczy tak zrobić:

[php:1:cb72611995]<?php
$template = preg_replace( "/<if condition="0">.*?</if>/is", "", $template );
$template = preg_replace( "/<if condition="1">(.*?)</if>/is", "1", $template );
?>[/php:1:cb72611995]

questionmark.gif
gulldarek
Ale ja chce miec mozliwosc wstawienia do szablonu byle jakiej zmiennej, czyli np. :

Kod
<if condition="$show">TRESC STRONY</if>


Kod
<if condition="$cos">INNA TRESC</if>


i teraz zeby skrypt jak znajdzie <if condition= sprawdzil o jaka zmienna chodzi (czyli np. $show) i sprawdzil czy ona jest true czy false. Jesli true to wyswietla kod miedzy <if></if> a w przeciwnym wypadku pomija go.
scanner
BzikOS - prawie, ale jeszcze zrób eval
Kod
condition=
gulldarek
Mam jeszcze edno pytanie:
Ten kod zwraca mi:

Kod
show">dsds


Jak rozbic ten tekst na tablice? Myslalem ze explode pomoze, ale przeciez miedzy
Kod
<if></if>
moze byc wiele znakow
Kod
">


Jest sposob zeby rozbic to na tablice ale jak natrafi sie na pierwszy
Kod
">
?
scanner
Napisałem Ci na PW, ale dodam też tutaj:
strpos() odnajduje pierwsze wystąpienie stringa i mozna mu nadać offset, od którego należy zacząć szukac.
BzikOS
Kontynuując mój pomysł.. coś takiego wykombinowałem:

[php:1:992871b632]<?php
$show = True;
$template = preg_replace( "/<if condition="(.*?)">(.*?)</if>/ie", "eval("return ('1' == True) ? '2' : '';")", $template );
?>[/php:1:992871b632]

Czy teraz o to chodzi? smile.gif
gulldarek
W zasadzie to jest dobrze, ale te zmienne trzeba jeszcze zglobalizowac...

no i z dodaniem <else> beda problemy tongue.gif
BzikOS
Z globalizacja to pestka:

[php:1:adc8287a03]<?php
preg_match_all( "/<if condition="(.*?)">.*?</if>/ie", $template, $out );
if( is_array( $out[1] ) )
eval("global " . implode( ', ', $out[1] ) . ";");
?>[/php:1:adc8287a03]

No a z else też pewnie dałoby się zrobić na pregach... trzeba tylko troche nad tym posiedzieć.
gulldarek
Kod
Parse error: parse error, expecting `T_VARIABLE' or `'$'' in c:usrkrasnalwwwcms_funkcje.php(55) : eval()'d code on line 1
BzikOS
A w szablonie masz zmienne z $ ?

[xml:1:1362f07aa0]<if condition="$show">TRESC STRONY</if>[/xml:1:1362f07aa0]
gulldarek
Tak mam.

Zrobilem cos takiego:

[php:1:d55d5f954c]<?php

function gettemplate($templatename, $gethtmlcomments = 1)
{

if(file_exists("templates/$templatename.htm")){

$fd = fopen ("templates/$templatename.htm", "r");

$template_file = fread ($fd, filesize ("templates/$templatename.htm"));
$template = preg_replace_callback('/{_([^ ]+)}/U', create_function('$matchs', 'return $GLOBALS["lang_$matchs[1]"];'), $template_file);
$template = preg_replace_callback('/{([^ ]+)}/U', create_function('$matches', 'return $GLOBALS[$matches[1]];'), $template);

preg_match_all( "/<if condition="(.*?)">.*?</if>/ie", $template, $out );
if(is_array($out[1])) eval('return $GLOBALS["$out[1]"];');

if ($options['addtemplatename'] = 1 AND $gethtmlcomments = 1)
{
$template = "n<!-- BEGIN TEMPLATE: $templatename -->n$templaten<!-- END TEMPLATE: $templatename -->n";
}

fclose($fd);

return $template;

} else {

return "<center><font color="red">Wystapil blad krytyczny - Brak szablonu '$tplfile'. Skontaktuj sie z administratorem.</font></center>";

}

}


?>[/php:1:d55d5f954c]

No ale pomimo tego, ze w skrypcie index.php zmienna $show jest ustawiona na false a ten skrypt korzysta z funkcji gettemplate nadal kod miedzy <if></if> sie wyswietla...
BzikOS
1. Coś pokopałeś.. skoro masz zmienne w tablicy superglobalnej to po co chcesz ją globalizowac?
2. Nie widze tu mojego preg_replace'a.
3. Jaką funkcję ma pełnić warunek if( $options['addtemplatename'] ... skoro stosujesz w nim operatory przypisania (=) a nie porównania (==)?
gulldarek
1. Ok twoje rozwiazanie dziala, ale zmienna musialem sam dodac do global, bo uzywajac kodu ktory mi dlaes do dodania jej do global otrzymywalem bledy jak w jednym z wczesniejszych postow. A oto ten kod:

[php:1:6f2f980378]<?php

// ##################### Start gettemplate ###########################
function gettemplate($templatename, $gethtmlcomments = 1)
{

global $options, $show;

if(file_exists("templates/$templatename.htm")){

$fd = fopen ("templates/$templatename.htm", "r");

$template_file = fread ($fd, filesize ("templates/$templatename.htm"));
$template = preg_replace_callback('/{_([^ ]+)}/U', create_function('$matchs', 'return $GLOBALS["lang_$matchs[1]"];'), $template_file);

$template = preg_replace_callback('/{([^ ]+)}/U', create_function('$matches', 'return $GLOBALS[$matches[1]];'), $template);

$template = preg_replace("/<if condition="(.*?)">(.+?)<else>(.+?)</if>/sie", "eval("return ('1' == true) ? '2' : '3';")", $template);

$template = preg_replace("/<if condition="(.*?)">(.+?)</if>/sie", "eval("return ('1' == true) ? '2' : '';")", $template);


if ($options['addtemplatename'] == 1 AND $gethtmlcomments == 1)
{
$template = "n<!-- BEGIN TEMPLATE: $templatename -->n$templaten<!-- END TEMPLATE: $templatename -->n";
}

fclose($fd);

return $template;

} else {

return "<center><font color="red">Wystapil blad krytyczny - Brak szablonu '$tplfile'. Skontaktuj sie z administratorem.</font></center>";

}

}


?>[/php:1:6f2f980378]
gulldarek
Jeszcze jedno

[php:1:4ba3768875]
<?php

$template = preg_replace("/<if condition="(.*?)">(.+?)</if>/sie",
"eval("return ('1' == true) ? '2' : '';")", $template);

?>
[/php:1:4ba3768875]



i dziala dobrze w przypadku zwyklych zmiennych. No ale wywala blad:

Kod
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in c:usrkrasnalwwwcms_funkcje.php(54) : regexp code on line 1



Fatal error: Failed evaluating code: eval("return ('$show['coppa']' == true) ? ' Zalogowany ' : ' Niezalogowany :) ';") in c:usrkrasnalwwwcms_funkcje.php on line 54



jak w szablonie zrobie

[xml:1:4ba3768875]<if condition="$show['cos']">dfdfdfd</if>[/xml:1:4ba3768875]


bez ['cos'] wszystko jest ok. Ktos wie jak to naprawic?
BzikOS
Powiem szczerze, że nie wiem :/ Męczyłem się z tym i nic ciekawego nie wyszło. Jedyny sposób jaki znalazłem (niezbyt elegancki i poprawny) to umieszczać indeks bez apostrofów - $show[cos] :/
gulldarek
Ok zrobiłem

[php:1:f536d9f0e9]
<?php

$template = preg_replace("/<if condition="(.*?)">(.+?)</if>/sie", "('1' == true) ? '2' : '';", $template);

?>
[/php:1:f536d9f0e9]

i nie ma juz bledow, ale mam problemy z wyswietleniem prawidlowej wartosci, bo pomimo, ze $show['coppa'] ustawione jest na false pokazuje sie kod ktory powinien wyswietlic sie gdy $show['coppa'] == false sad.gif
?>[/php]
BzikOS
Hahaha jasne że teraz nie będzie błędów bo nie ma prawa być - wyrzuciłes najważniejszy element czyli eval, a więc nic nie jest porównywane / sprawdzane bo jest to traktowane jako zwykły ciąg, a nie jako kod php - czyli nie zrobiłes, a wręcz oddaliłeś się od rozwiązania.
gulldarek
Cytat
Hahaha jasne że teraz nie będzie błędów bo nie ma prawa być - wyrzuciłes najważniejszy element czyli eval, a więc nic nie jest porównywane / sprawdzane bo jest to traktowane jako zwykły ciąg, a nie jako kod php - czyli nie zrobiłes, a wręcz oddaliłeś się od rozwiązania.


tak mi poradzili na kanale #php pewnego serwera winksmiley.jpg (stwierdzili ze /e juz mi dodaje eval czy jakos tak tongue.gif ).

Ok, to moze inaczej to zrobic? np usunac znaki ' ' w skrypcie?
BzikOS
Znalazłem w końcu chwilę czasu i wymyśliłem coś takiego:

[php:1:5fd2019653]<?php
function rep( $x )
{
eval( "global " . preg_replace( "/[.*]/", '', $x[1] ) . "; " );
eval( 'if( ' . $x[1] . ' == True ) $z= ' . $x[2] . '; else $z = '';' );
return( $z );
}

$template = preg_replace_callback("/<if condition="(.*?)">(.+?)</if>/siU", 'rep', $template);
?>[/php:1:5fd2019653]

U mnie działa smile.gif


btw. php Początkujący => php
gulldarek
Ok twoje dziala dobrze, ale ja w miedzy czasie tez znalazlem sposob i juz dziala smile.gif (ale zastosowalem twoj sposob!)

[php:1:e239da0aad]<?php

function parseTemplateIffound($template)
{

$thePattern = '!<if condition="(.*?)">(.*?)<else>(.*?)</if>!ism';
preg_match_all($thePattern, $template, $theBackRef);
for ($i = 0; $i < count($theBackRef[0]); $i++)
{
if ($show[$theBackRef[1][$i]] == true)
{
$template = str_replace($theBackRef[0][$i], $theBackRef[2][$i], $template);
}
else
{
$template = str_replace($theBackRef[0][$i], $theBackRef[3][$i], $template);
}
}
return $template;
}

?>[/php:1:e239da0aad]

EDIT: ALe co bedzie jak zrobie cos takiego:

[xml:1:e239da0aad]

<if condition="$show['register']">Zarejestrowany<if condition="$show['username']">$username</if><else>Niezarejestrowany</if>
[/xml:1:e239da0aad]

Sa dwa ify a skrypt pewnie pomysli ze pierwsze </if> zamyka <if condition="$show['register']">
BzikOS
Cytat
Sa dwa ify a skrypt pewnie pomysli ze pierwsze </if> zamyka <if condition="$show['register']">

Zgadza się, do instrukcji zagnieżdżonych mój sposób Ci się nie przyda. W ogóle czy gra jest warta świeczki? Bo w takiej sytuacji to trzeba by napisać własny parser. Pytanie - czy opłaca się to robić?
gulldarek
Oplaca, oplaca smile.gif

Co do wlasnego parsera to probowalem wykorzystac sposob z vbulletina no ale cos mi nie wychodzilo. Moze potem wkleje ta funkcje.
Bora
hmm może warto siem tym zainteresowac żeby pozbyć sie smarty.Przecież i tak sie korzysta z prostych rzeczy jak pętle if'y.
A może dzęki temu zyska sie na wydajności.

Kiredyś też pisałem własny system templetów i bardzo mnie to interesuje.

A co do tego sposobu z vb , jakbyś mógł podaj go , napewno też warto sie z nim zapoznać .
gulldarek
[php:1:8770f4a600]<?php
function process_template_conditionals($template, $haltonerror = true)
{
global $vb script:history.back(1)'));
print_cp_footer();
}
}
}

if ($template_cond[$condition_end + 2] != '>')
{ // the > doesn't come right after the condition must be malformed
$if_end_location = $if_location + 1;
continue;
}

// look for recursive case in the if block -- need to do this so the correct </if> is looked at
$recursive_if_loc = $if_location;
while (1)
{
$recursive_if_loc = strpos($template_cond, $if_lookfor, $recursive_if_loc + 1); // find an if case
if ($recursive_if_loc === false OR $recursive_if_loc >= $if_end_location)
{ //not found or out of bounds
break;
}

// the bump first level's recursion back one </if> at a time
$recursive_if_end_loc = $if_end_location;
$if_end_location = strpos($template_cond, $if_end_lookfor, $recursive_if_end_loc + 1);
if ($if_end_location === false)
{
return str_replace("'", "'", $template_cond); // no </if> found -- return the original template
}
}

$else_location = strpos($template_cond, $else_lookfor, $condition_end + 3); // location of false portion

// this is needed to correctly identify the <else /> tag associated with the outermost level
while (1)
{
if ($else_location === false OR $else_location >= $if_end_location)
{ // else isn't found/in a valid area
$else_location = -1;
break;
}

$temp = substr($template_cond, $condition_end + 3, $else_location - $condition_end + 3);
$opened_if = substr_count($temp, $if_lookfor); // <if> tags opened between the outermost <if> and the <else />
$closed_if = substr_count($temp, $if_end_lookfor); // <if> tags closed under same conditions
if ($opened_if == $closed_if)
{ // if this is true, we're back to the outermost level
// and this is the correct else
break;
}
else
{
// keep looking for correct else case
$else_location = strpos($template_cond, $else_lookfor, $else_location + 1);
}
}

if ($else_location == -1)
{ // no else clause
$read_length = $if_end_location - strlen($if_end_lookfor) + 1 - $condition_end + 1; // number of chars to read
$true_value = substr($template_cond, $condition_end + 3, $read_length); // the true portion
$false_value = '';
}
else
{
$read_length = $else_location - $condition_end - 3; // number of chars to read
$true_value = substr($template_cond, $condition_end + 3, $read_length); // the true portion

$read_length = $if_end_location - strlen($if_end_lookfor) - $else_location - 3; // number of chars to read
$false_value = substr($template_cond, $else_location + strlen($else_lookfor), $read_length); // the false portion
}

if (strpos($true_value, $if_lookfor) !== false)
{
$true_value = process_template_conditionals($true_value);
}
if (strpos($false_value, $if_lookfor) !== false)
{
$false_value = process_template_conditionals($false_value);
}

// clean up the extra slashes
$str_find = array('"', '');
$str_replace = array('"', '');
if ($delimiter == "'")
{
$str_find[] = "'";
$str_replace[] = "'";
}

$str_find[] = '$delimiter';
$str_replace[] = $delimiter;

$condition_value = str_replace($str_find, $str_replace, $condition_value);

$conditional = "" . (($condition_value) ? ("$true_value") : ("$false_value"))."";
$template_cond = substr_replace($template_cond, $conditional, $if_location, $if_end_location + strlen($if_end_lookfor) - $if_location);

$if_end_location = $if_location + strlen($conditional) - 1; // adjust searching position for the replacement above
}

return str_replace("'", "'", $template_cond);
}
?>[/php:1:8770f4a600]
gulldarek
Dziala mi juz sprawdzanie, ale zrobilem troche inaczej. Znaczniki musza wygladac tak:

[xml:1:0d9ab2f477]<if condition="($cos['cos'] == 1)">COS<else />NIE COS</if condition="($cos['cos'] == 1)">[/xml:1:0d9ab2f477]

Ok, ostatnia wersja mojego systemu szablonow wyglada tak:

[php:1:0d9ab2f477]<?php
// ##################### Start gettemplate ###########################
function gettemplate($templatename, $print = 0, $gethtmlcomments = 1)
{
global $options, $show;

if(file_exists("templates/$templatename.htm"))
{
$fd = fopen ("templates/$templatename.htm", "r");

$template_file = fread ($fd, filesize ("templates/$templatename.htm"));
$template = preg_replace_callback('/{_([^ ]+)}/U', create_function('$matchs', 'return $GLOBALS["lang_$matchs[1]"];'), $template_file);
$template = str_replace('{script}', SCRIPT.'.php', $template);
$template = preg_replace_callback('/{([^ ]+)}/U', create_function('$matches', 'return $GLOBALS[$matches[1]];'), $template);

if (substr_count($template,'</if') >= 1)
{
$template = template_conditionals($template);
}

if ($options['addtemplatename'] == 1 AND $gethtmlcomments == 1)
{
$template = "rn<!-- BEGIN TEMPLATE: " . $templatename . " -->n" . $template . "n<!-- END TEMPLATE: " . $templatename . " -->rn";
}

if ($options['templatecompressor'] == 1)
{
//$page_byte = strlen($template);
$template = preg_replace ("/(>)(s*)(rn)*(s*)(<)/", '15', $template);

//$pagenew_byte=strlen($template);
//$page_kilobyte=number_format(($page_byte/1024),2); // echo strpos($vartext,">rn<");exit;
//$pagenew_kilobyte=number_format(($pagenew_byte/1024),2);
//$pagesaved_byte=$page_byte-$pagenew_byte;
//$pagesaved_kilobyte=number_format((($pagesaved_byte)/1024),2);
//$pagesaved_perc=number_format(((100*$pagesaved_byte)/$page_byte),2);

//$output .= "<br> [Prawdziwa "waga": " . $page_kilobyte . " Kb. skompresowana do <b>" . $pagenew_kilobyte . "</b> Kb. oszczedzajac <b>" . $pagesaved_kilobyte . "</b> Kb. (" . $pagesaved_perc% . ")] ";
}

fclose($fd);

if ($print == 1)
{
echo $template;
}
else
{
return $template;
}

}
else
{

$errormsg = "<center><font color='red'>Wystapil blad krytyczny - Brak szablonu " . $templatename . ".<br>Skontaktuj sie z administratorem.</font></center>";

if ($print == 1)
{
echo $errormsg;
}
else
{
return $errormsg;
}
}
}

// ##################### Start template_conditionals ###########################
function template_conditionals($template)
{
@extract($GLOBALS, EXTR_SKIP);

while (preg_match('/<if condition="(.*)">(.*)</if condition="1">/siU',$template,$condition))
{
if (substr_count($condition[2],'<else />') >= 1)
{
preg_match('/<if condition="(.*)">(.*)<else />(.*)</if condition="1">/siU',$condition[0],$condition_else);
$condition_true = $condition_else[2];
$condition_false = $condition_else[3];
}
else
{
$condition_true = $condition[2];
$condition_false = '';
}

@eval ('if ('.stripslashes($condition[1]).') { $eval_deger= "1"; } else { $eval_deger= "0"; }');

if ($eval_deger==1)
{
$template=str_replace($condition[0], $condition_true, $template);
}
else
{
$template=str_replace($condition[0], $condition_false, $template);
}
}

return $template;
}
?>[/php:1:0d9ab2f477]
Bora
Może mój template ciebie zainteresuje.
Posiada obsługe multisesji, ifów. nie przeszkadzają mu złożone konstrukcje.

Plik: tpl_page.php
[php:1:9e5c7bc94c]<?php
<?php
include('tpl_class.php');
$tpl= new template('.');
$tpl->Assign("config_test",array(array('configa1v','configb2v','configc3v')));
$tpl->Assign("config_value",array('name'=>array('aaa1n','bbbb2n','cccc3n'),
'value'=>array('aaa1v','bbbb2v','cccc3v'),
'val'=>array('1','0','1'),
'vals'=>array('1','1','0')));
$tpl->Assign("config_values",array('name'=>array('sa1n','sb2n',),
'value'=>array('sa1v','sb2v','sc3v')));
$tpl->Assign("config_valued",array('name'=>array('da1n','db2n','db3n'),
'value'=>array('da1v','db2v','db3v')));
$tpl->Assign("config_v",array('names'=>array('da1n','db2n','db3n')));
$tpl->Assign("config_val",array('names'=>array('valda1n')));
$tpl->Assign("config_valr",array('names'=>array('valrrrrda1n')));
$tpl->Assign("config_vale",array('names'=>array('val@')));
$tpl->Assign('tpl','templates');
$tpl->Assign('i','1');
echo $tpl->Display('tpl');
?>
?>[/php:1:9e5c7bc94c]

Plik: tpl_class.php:
[php:1:9e5c7bc94c]<?php
<?php
class template
{
var $parsed;
var $unparse;
var $blocks;
var $dir;

//function __construct($dir)
function template($dir)
{
$this->_setDir($dir);
}

function _setDir($dir)
{
if (is_dir($dir))
{
$this-> dir = $dir;
return true;
}
else
{
die("[TEMPLATE]Root dir no exists!");
}
}
function Assign($var, $value=null)
{
if (is_array($value))
{
$klucze = array_keys($value);
foreach ($klucze as $klucz)
{
foreach ($value[$klucz] as $val)
{
$this -> blocks[$var][$klucz][] = $val;
}
}
}else{
$this -> blocks[$var] = $value;
}
}

function Display($file)
{
if (!file_exists($dir . $file . '.tpl'))
{
return false;
}
$this -> unparse = file($dir . $file . '.tpl');
$fh = fopen($dir . $file . '.tpl', "r");
$this -> unparse = chop(fread($fh, filesize($dir . $file . '.tpl')));
$i=0;
while ( ereg( "{section name=(.*)}(.*){/section}|{if (.*)}(.*){/if}", $this->unparse) )
{
$this -> _parseTab();
++$i;
//echo $i;
if ($i>20){exit('Osiagnieto stan krytyczny sprawdz poprawnosc kodu'.$this->unparse);}
}
$this -> unparse = $this->_parse($this -> unparse);
//$this -> unparse = preg_replace("{(.+?)}", '', $this -> unparse);
return $this -> unparse ;
}

function _parseTab()
{
$line = $this -> unparse;
preg_match("/{if (.+?)}|{section name=(.+?)}/", $line, $found);
if (ereg("section", $found[0]))
{
preg_match( "/{section name=(.+?)}(.*?){/section}/is", $line, $found);
$deep_begin = substr_count($found['0'], '{section name=');
$deep_end = substr_count($found['0'], '{/section}');
$i==0;
while ($deep_end != $deep_begin)
{
++$i;
$var="(.*?){/section}";
$vars="";
for ($j=0;$j<$i;++$j)
{
$vars.=$var;
}
preg_match( "/{section name=(.+?)}{$vars}(.*?){/section}/is", $line, $found);
$deep_begin = substr_count($found['0'], '{section name=');
$deep_end = substr_count($found['0'], '{/section}');

if ($i>20){exit('Osiagnieto stan krytyczny sprawdz poprawnosc kodu w sprawdzaniu struktury');}
}
$string_replaced = $found['0'];
$end = strlen($string_replaced);
$begin = 15+strlen($found['1']);
$string = substr($found['0'], $begin, $end-10-$begin);
preg_match('/{section name=(.+?)}(.+?){/section}/ms', $found['0'],$match);
$line = str_replace( $string_replaced, $this->_parse_intab($string,$found['1']),$line);
$line = str_replace('{tmp}', '', $line);
$this->unparse = $line;
}else{
$i=0;
$deep_end=1;
$deep_begin=0;
while ($deep_end != $deep_begin)
{
$var="(.+?){/if}";
$vars="";
for ($j=0;$j<$i;++$j)
{
$vars.=$var;
}
preg_match( "/{if (.+?)}(.+?){/if}$vars/is", $line, $found);
$deep_begin = substr_count($found['0'], '{if');
$deep_end = substr_count($found['0'], '{/if}');
++$i;
if ($i>20){exit('Osiagnieto stan krytyczny sprawdz poprawnosc kodu w sprawdzaniu struktury');}
}
$warunek=explode('==',$found['1']);
$all = strlen($found['0']);
$warunek['0']=str_replace('$', '', $warunek['0']);
$warunek['0']=str_replace(' ', '', $warunek['0']);
$warunek['1']=str_replace(' ', '', $warunek['1']);
$if ='if('.$this->blocks[$warunek['0']] .'=='. $warunek['1'].'){$op=1;}else{$op=0;}';
eval($if);
$deep_end = 1;
$deep_begin = 0;
$i=0;
while ($deep_end != $deep_begin)
{
$var="(.+?){/if}";
$vars="";
for ($j=0;$j<$i;++$j)
{
$vars.=$var;
}
preg_match( "/{if (.+?)}$vars(.+?){else}/is", $line, $match);
$deep_begin = substr_count($match['0'], '{if');
$deep_end = substr_count($match['0'], '{/if}')+1;
++$i;
if ($i>20){exit('Osiagnieto stan krytyczny sprawdz poprawnosc kodu w sprawdzaniu struktury');}
}
$allif = strlen($match['0']);
$begin = strlen($match['1']);
if ($op==1)
{
$string = substr($match['0'], $begin+5, $allif-$begin-11);
$line = str_replace($found['0'], $string,$line);
$this->unparse = $line;
}else{
$string = substr($match['0'], $begin+5, $allif-$begin-11);
$else=substr($found['0'],$allif,$all-$allif-5);
$line = str_replace($found['0'], $else,$line);
$this->unparse = $line;
}
}
return false;
}

function _parse($line)
{
$found = array();
if(preg_match_all("#{(.+?)}#is", $line, $found))
{
foreach ($found['1'] as $block)
{
$block = str_replace('$', '', $block);
$block_names='{$'.$block.'}';
$block_values = $this -> blocks[$block];
$line = str_replace($block_names, $block_values, $line);
}
$line = str_replace($block_names, $block_values, $line);
}
return $line;
}

function _parse_intab($line,$mod)
{
$found = array();
if(preg_match_all("#{$[{$mod}].(.+?)}#ms", $line, $found))
{
foreach ($found['1'] as $block)
{
$block_names='{$['.$mod."].".$block.'}';
$block_values = $this->blocks[$mod][$block];
$count_var = count($this->blocks[$mod][$block]);
if (!empty($count_var))
{
if (!empty($lines))
{
$lines=explode('{tmp}',$lines);
for ($i=0;$i<$count_var;++$i)
{
$lines[$i] = str_replace($block_names, $block_values[$i], $lines[$i]);
}
$lines=implode('{tmp}',$lines);
}else{
for ($i=0;$i<$count_var;++$i)
{
$lines[$i] = str_replace($block_names, $block_values[$i], $line);
}
$lines=implode('{tmp}',$lines);
}
}else{
$lines="";
}
}
}
return $lines;
}
}
?>
?>[/php:1:9e5c7bc94c]
Plik tpl.tpl:
Kod
test Parsera - {$tpl}-

<table border="1">

  {section name=config_value}

  {if $i == {$[config_value].val}}

    <tr>

      <td>[deep:

     {if $i == {$[config_value].vals}}1{else}2{/if}

   :

        {if $i == {$[config_value].vals}}1{else}2{/if}

   :

        {if $i == {$[config_value].vals}}1{else}2{/if}

   :

        {if $i == {$[config_value].vals}}

     1{if $i == {$[config_value].value}}p{else}q{/if}

     {else}2{/if}

   ]</td>

      <td>[{$[config_value].name}]</td>

      <td>[{$[config_value].value}]</td>

    </tr>

    {else}

    <tr>

      <td>[deep:

  {if $i == 1}[1o]{else}[2o]{/if}

  {if $i == 0}[1e]{else}[2e]{/if}

  ]</td>

      <td>[null]</td>

      <td>[null]</td>

    </tr>

    {/if}

    {/section}

</table>



Sprawdzanie czy interpretuje błędny zapis:

{section}dfdff{/section}

{if $i ==8}eee{else}
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.