PHP Regular Expressions-imitation smarty

Source: Internet
Author: User
/**
The class name Smarty is a custom template engine
The template file is loaded and parsed by the class object, and the parsed result is output
*/
Class Smarty {
Public $template _dir = ' templates '; Define the directory where template files are stored
Public $compile _dir = ' Templates_c '; Define the file directory after the template engine is combined
Public $left _delimiter = ' <{';//embed the left-bound symbol of the dynamic Data variable in the template
Public $right _delimiter = '}> '; Embed a right-bound symbol for a dynamic data variable in a template
Private $TPL _vars = Array (); Temporary variables for internal use

/**
The values assigned in PHP are saved to the member property $tpl_vars, which is used to replace the corresponding variables in the board
@paramString$TPL _varA string parameter is required as an associative array subscript, which corresponds to the variable name in the template
@paramMixed$valueA value of scalar type is required to assign to the value of a variable in the template
*/
function assign ($tpl _var, $value = null) {
if ($tpl _var! = ")
$this->tpl_vars[$tpl _var] = $value;
}

/**
Loads the template file under the specified directory and stores the replaced content generation combination file in another specified directory
@paramString$fileNameProvide file name for template files
*/
function display ($fileName) {
/* Find the template file in the specified directory */
$tplFile = $this->template_dir. '/'. $fileName;
/* Exit and report an error if the template file that needs to be processed does not exist */
if (!file_exists ($tplFile)) {
Die ("template file {$tplFile} does not exist! ");
}
/* Gets the combined template file, the contents of which are replaced by */
$comFileName = $this->compile_dir. " /com_ ". $fileName. PHP ';
/* To determine if the replaced file exists or exists but has changed, it needs to be recreated */
if (!file_exists ($comFileName) | | filemtime ($COMFILENAME) < Filemtime ($tplFile)) {
/* Invoke Internal replacement Template method */
$repContent = $this->tpl_replace (file_get_contents ($tplFile));
/* Save the script file that was assembled by the system */
File_put_contents ($comFileName, $repContent);
}
/* Contains the processed template file output to the client */
Include ($comFileName);
}

/**
Private methods used internally, using regular expressions to replace the statements in the template file ' <{}> ' with corresponding values or PHP code
@paramString$contentProvides a full string of content that is read from the template file
@return$repContentReturns the replaced string
*/
Private Function Tpl_replace ($content) {
/* Leave the left and right bounding symbols, with special symbols that affect the regular sign escape for example, <{}> escape \<\{\}\> */
$left = Preg_quote ($this->left_delimiter, '/');
$right = Preg_quote ($this->right_delimiter, '/');
/* pattern array of regular expressions that match the various identifiers in the template */
$pattern = Array (
/* Match the variables in the template, for example, "<{$var}>" */
'/'. $left. ' \s*\$ ([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \s* '. $right. ' /I ',
/* Match the If identifier in the template, such as "<{if $col = =" Sex "}> <{/if}>" * *
'/'. $left. ' \s*if\s* (. +?) \s* '. $right. ' (.+?)'. $left. ' \s*\/if\s* '. $right. ' /ies ',
/* Match ElseIf identifiers, such as "<{elseif $col = =" Sex "}>" */
'/'. $left. ' \s*else\s*if\s* (. +?) \s* '. $right. ' /ies ',
/* Match else identifier, for example "<{else}>" */
'/'. $left. ' \s*else\s* '. $right. ' /is ',
/* is used to match the loop identifier in the template to iterate through the values in the array, such as "<{loop $arrs $value}> <{/loop}>" */
'/'. $left. ' \s*loop\s+\$ (\s+) \s+\$ ([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \s* '. $right. ' (.+?)'. $left. ' \s*\/loop\s* '. $right. ' /is ',
/* is used to iterate through the keys and values in the array, such as "<{loop $arrs $key = = $value}> <{/loop}>" */
'/'. $left. ' \s*loop\s+\$ (\s+) \s+\$ ([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \s*=>\s*\$ (\s+) \s* '. $right. ' (.+?)'. $left. ' \s*\/loop \s* '. $right. ' /is ',
/* Match the include identifier, for example, ' <{include ' header.html '}> ' */
'/'. $left. ' \s*include\s+[\ "\ '"? (.+?) [\ ' \ ']?\s* '. $right. ' /ie '
);

/* Replace the array of strings that are matched to the regular expression from the template */
$replacement = Array (
/* Replace the variables in the template Tpl_vars["var"]; */
' tpl_vars["${1}"];?> ',
/* Replace the IF string in the template */
' $this->stripvtags (\ ' \ ', \ ' ${2} \')',
/* Replace the ElseIf string */
' $this->stripvtags (\ ' \',"")',
/* Replace the Else string */
' ',
/* The following two are used to replace the loop identifier in the template with the foreach format */
' tpl_vars["${1}"] as $this->tpl_vars["${2}"]) {? >${3} ',
' tpl_vars["${1}"] as $this->tpl_vars["${2}"] = = $this->tpl_vars["${3}"]) {? >${4} ',
/* Replace the Include string */
' File_get_contents ($this->template_dir. " /${1} ") '
);

/* Use regular replace function to process */
$repContent = Preg_replace ($pattern, $replacement, $content);
/* If there is an identity to replace, recursively call yourself to replace */
if (Preg_match ('/'. $left. ' ([^ ('. $right. ')] {1,}) '. $right. ' /', $repContent)) {
$repContent = $this->tpl_replace ($repContent);
}
/* Returns the replaced String */
return $repContent;
}

/**
Private method used internally to replace the variable used in the conditional statement with the corresponding value
@paramString$exprProvides the start tag of a conditional statement in a template
@paramString$statement provide a closing tag for a conditional statement in a template
@returnStrinReturns after the processed conditional statement is connected
*/
Private Function Stripvtags ($expr, $statement = ") {
/* Match variable's regular */
$var _pattern = '/\s*\$ ([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \s*/is ';
/* Replace the variable with a value */
$expr = Preg_replace ($var _pattern, ' $this->tpl_vars[' ${1} "] ', $expr);
/* Escape the quotation marks in the start tag by replacing */
$expr = Str_replace ("\\\" "," \ "", $expr);
/* Replace quotation marks in statement body and closing tag */
$statement = Str_replace ("\\\" "," \ "", $statement);
/* Returns the processed conditional statement to the back */
return $expr. $statement;
}
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The above describes the PHP regular expression-imitation smarty, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.