This feature, βmapβ (and replacement), is part of my web application system:
function replace($search, $replace, $mixed) { if (is_string($mixed)) { return @str_replace($search, $replace, $mixed); } else if (is_array($mixed)) { foreach ($mixed as $k => $v) { $mixed[$k] = replace($search, $replace, $v); } return $mixed; } else { return $mixed; } } function map($a, $contents, $case_sensitive=false) { if (!is_array($a)) { return $contents; } if (!$case_sensitive) { $a = array_change_key_case($a); } $s = array(); $r = array(); foreach ($a as $k => $v) { if (is_scalar($v) || empty($v)) { $s[] = "{".$k."}"; $r[] = $v; } } if (!$case_sensitive) { $contents = preg_replace_mixed('/{([-_ =,.\/\'"A-Za-z0-9]+)}/ei', "'{'.strtolower('\\1').'}'", $contents); } return replace($s, $r, $contents); }
Great job. Supply any string with variable names in square brackets, and this does the trick.
The syntax is different, but can be changed for your purposes:
$str = map(array('name' => 'Joe'), 'My name is {name}');
I prefer it over the% syntax.
source share