linccce

HTML Mini parser

May 3rd, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.83 KB | None | 0 0
  1. class html_parser
  2. {
  3.     public static function trim_multichar($str, $chars) {
  4.         foreach (str_split($chars) as $char) {
  5.             $str = trim($str, $char);
  6.         }
  7.  
  8.         return $str;
  9.     }
  10.  
  11.     public static function trim_all($array, $chars) {
  12.         foreach ($array as $key => $el) {
  13.             $array[$key] = self::trim_multichar($el, $chars);
  14.         }
  15.  
  16.         return $array;
  17.     }
  18.  
  19.     public static function parse_tpl($html, $data = array()) {
  20.         // functions
  21.         $matches = array();
  22.         preg_match('/\s{%(.*?)%}\s/', $html, $matches);
  23.         while (count($matches)) {
  24.             $match = trim($matches[0]);
  25.             $params = self::trim_multichar($match, "{%}% ");
  26.             $params = explode('|', $params);
  27.             $f = trim($params[0]);
  28.             if (function_exists($f)) {
  29.                 if (count($params) > 1) {
  30.                     unset($params[0]);
  31.                     $params = array_merge($params, array());
  32.                 }
  33.  
  34.                 $ret = call_user_func_array($f, $params);
  35.                 if ($ret !== false) {
  36.                     $html = str_replace($match, $ret, $html);
  37.                 }
  38.             } else {
  39.                 break;
  40.             }
  41.  
  42.             preg_match('/(\s{%.*?%}\s)/', $html, $matches);
  43.         }
  44.  
  45.         // variables from $data
  46.         $matches = array();
  47.         preg_match('/{{(.*?)}}/', $html, $matches);
  48.  
  49.         while (count($matches)) {
  50.             $match = trim($matches[0]);
  51.             $key = self::trim_multichar($match, "{} ");
  52.             $replace = '';
  53.             if (isset($data[$key])) {
  54.                 $replace = $data[$key];
  55.             }
  56.             $html = str_replace($match, $replace, $html);
  57.  
  58.             preg_match('/{{(.*?)}}/', $html, $matches);
  59.         }
  60.  
  61.         return $html;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment