Skip to content

Instantly share code, notes, and snippets.

@bastman
Created February 1, 2012 13:06
Show Gist options
  • Save bastman/1716909 to your computer and use it in GitHub Desktop.
Save bastman/1716909 to your computer and use it in GitHub Desktop.
str replace (php) - for a simple template engine
function replace ($text, array $replace) {
// @see: http://www.php.net/manual/en/function.strtr.php#106282
$text = "".$text;
$keys = array_keys($replace);
$length = array_combine($keys, array_map('strlen', $keys));
arsort($length);
$array[] = $text;
$count = 1;
reset($length);
while ($key = key($length)) {
if (strpos($text, $key) !== false) {
for ($i = 0; $i < $count; $i += 2) {
if (($pos = strpos($array[$i], $key)) === false) {
continue;
}
array_splice(
$array,
$i,
1,
array(
substr($array[$i], 0, $pos),
$replace[$key],
substr($array[$i], $pos + strlen($key))
)
);
$count += 2;
}
}
next($length);
}
return implode("", $array);
}
$template = "INSERT INTO table3={{table3}} table2={{table2}} table1={{table1}} table3={{table3}} table={{table}} FOO table={{table}} BAR table table2={{table2}} table3={{table3}}";
// $r=subtok($template, "{{table}}",0, null);
//$r = tokenize($template, "{{table}}");
$r = replace($template, array(
"{{table}}" => "TABLE",
"{{table2}}"=> "{{table1}}",
"{{table1}}"=> "TABLE1",
"{{table3}}"=> "{{table3}}",
));
// as you see: protected from nesting templates
var_dump($r);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment