note 95987 added to function.substr

From: Date: Mon, 01 Feb 2010 20:46:04 +0000
Subject: note 95987 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-165573@lists.php.net to get a copy of this message
I've seen numerous requests over the years from people trying to put together templating systems using XML parsers or regular expressions - you can create a simple template system with the following class. It could easily be expanded to take advantage of parameters, conditionals, etc. <?php class Template { const OPEN_BRACKET = "{"; const CLOSE_BRACKET = "}"; public static function inject(array $source, $template) { $ob_size = strlen(self::OPEN_BRACKET); $cb_size = strlen(self::CLOSE_BRACKET); $pos = 0; $end = strlen($template); while($pos <= $end) { if($pos_1 = strpos($template, self::OPEN_BRACKET, $pos)) { if($pos_1) { $pos_2 = strpos($template, self::CLOSE_BRACKET, $pos_1); if($pos_2) { $return_length = ($pos_2-$cb_size) - $pos_1; $var = substr($template, $pos_1+$ob_size, $return_length); $template = str_replace(self::OPEN_BRACKET.$var.self::CLOSE_BRACKET, $source[$var], $template); $pos = $pos_2 + $cb_size; } else { throw new exception("Incorrectly formed template - missing closing bracket. Please check your syntax."); break; } } } else { //exit the loop break; } } return $template; } } //array of values to inject into the template $array = array("NAME" => "John Doe", "DOB" => "12/21/1986", "ACL" => "Super Administrator"); //template using '{' and '}' to signify variables $template = "This is your template, {NAME}. You were born on {DOB} and you are a {ACL} on this system."; echo Template::inject($array, $template); ---- Server IP: 64.71.164.2 Probable Submitter: 216.201.124.166 ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit -- https://master.php.net/note/edit/95987 Del: integrated -- https://master.php.net/note/delete/95987/integrated Del: useless -- https://master.php.net/note/delete/95987/useless Del: bad code -- https://master.php.net/note/delete/95987/bad+code Del: spam -- https://master.php.net/note/delete/95987/spam Del: non-english -- https://master.php.net/note/delete/95987/non-english Del: in docs -- https://master.php.net/note/delete/95987/in+docs Del: other reasons-- https://master.php.net/note/delete/95987 Reject -- https://master.php.net/note/reject/95987 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#165573) next »