Php regular expression-like smarty

Source: Internet
Author: User
Tags php regular expression
: This article mainly introduces the php regular expression-like smarty. if you are interested in the PHP Tutorial, refer to it. /**
The class name Smarty is a custom template engine.
Load and parse the template file using this type of object, and output the parsed result
*/
Class Smarty {
Public $ template_dir = 'templates'; // defines the directory where the template file is stored.
Public $ compile_dir = 'Templates _ C'; // defines the file storage directory after the template engine is combined.
Public $ left_delimiter = '<{'; // The left delimiter of the dynamic data variable embedded in the template
Public $ right_delimiter = '}>'; // The right delimiter of the dynamic data variable embedded in the template
Private $ tpl_vars = array (); // temporary variable used internally

/**
Save the value allocated in PHP to the member attribute $ tpl_vars to replace the corresponding variable in the board.
@ Paramstring $ tpl_var a string parameter must be used as the subscript of the associated array. it must correspond to the variable name in the template.
@ Parammixed $ value requires a scalar value to be assigned to the variable value in the template.
*/
Function assign ($ tpl_var, $ value = null ){
If ($ tpl_var! = '')
$ This-> tpl_vars [$ tpl_var] = $ value;
}

/**
Load the template file under the specified directory, and store the generated combined file of the replaced content to another specified directory.
@ Paramstring $ fileName provides the template file name
*/
Function display ($ fileName ){
/* Search for the template file in the specified directory */
$ TplFile = $ this-> template_dir. '/'. $ fileName;
/* If the template file to be processed does not exist, exit and report an error */
If (! File_exists ($ tplFile )){
Die ("template file {$ tplFile} does not exist! ");
}
/* Obtain the combined template file. the content in this file is replaced */
$ ComFileName = $ this-> compile_dir. "/com _". $ fileName. '. php ';
/* To determine whether the replaced file exists or exists but has been changed, you must create a new one */
If (! File_exists ($ comFileName) | filemtime ($ comFileName) <filemtime ($ tplFile )){
/* Call the internal replacement Template method */
$ RepContent = $ this-> tpl_replace (file_get_contents ($ tplFile ));
/* Save the script file after the system combination */
File_put_contents ($ comFileName, $ repContent );
}
/* Include the processed template file and output it to the client */
Include ($ comFileName );
}

/**
Use a regular expression to replace the statements in the '<{}>' template file with the corresponding values or PHP code.
@ Paramstring $ content: all content strings read from the template file
@ Return $ repContent returns the replaced string
*/
Private function tpl_replace ($ content ){
/* Escape special characters that affect regular expressions in the left and right delimiters, for example, <{}> escape \ <\{\}\> */
$ Left = preg_quote ($ this-> left_delimiter ,'/');
$ Right = preg_quote ($ this-> right_delimiter ,'/');
/* Regular expression pattern array matching 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, for example, "<{if $ col =" sex "}>< {/if}> "*/
'/'. $ Left. '\ s * if \ s * (. + ?) \ S * '. $ right.' (. + ?) '. $ Left.' \ s * \/if \ s * '. $ right.'/ies ',
/* Match the elseif identifier, for example, "<{elseif $ col =" sex "}> "*/
'/'. $ Left. '\ s * else \ s * if \ s * (. + ?) \ S * '. $ right.'/ies ',
/* Match the else identifier, for example, "<{else}> "*/
'/'. $ Left. '\ s * else \ s *'. $ right. '/is ',
/* Matches the loop identifier in the template to traverse the values in the array, for example, "<{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 ',
/* Used to traverse keys and values in the array, for example, "<{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 string array matched by the regular expression in 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 items 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 the regular expression replacement function for processing */
$ RepContent = preg_replace ($ pattern, $ replacement, $ content );
/* If there are other identifiers to be replaced, recursively call and replace them again */
If (preg_match ('/'. $ left. '([^ ('. $ right. ')] {1 ,})'. $ right. '/', $ repContent )){
$ RepContent = $ this-> tpl_replace ($ repContent );
}
/* Return the replaced string */
Return $ repContent;
}

/**
The private method used internally to replace the variables used in the condition statement with the corresponding values.
@ Paramstring $ expr provides the start mark of the condition statement in the template.
@ Paramstring $ statement: End mark of the condition statement in the template
@ Returnstrin connect the processed condition Statement and Return
*/
Private function stripvtags ($ expr, $ statement = ''){
/* Match the regular expression of the variable */
$ Var_pattern = '/\ s * \ $ ([a-zA-Z _ \ x7f-\ xff] [a-zA-Z0-9 _ \ x7f-\ xff] *) \ s */is ';
/* Replace the variable with the value */
$ Expr = preg_replace ($ var_pattern, '$ this-> tpl_vars ["$ {1}"]', $ expr );
/* Replace the quotation mark escape in the start mark */
$ Expr = str_replace ("\\\" "," \ "", $ expr );
/* Replace the quotation marks in the statement body and end mark */
$ Statement = str_replace ("\\\" "," \ "", $ statement );
/* Connect the processed condition statement and return the result */
Return $ expr. $ statement;
}
}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

The above introduces the php regular expression-like smarty, including the content, hope to be helpful to friends interested in PHP tutorials.

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.