PHP String Tokenizer
Function for replacing tokens in a string
This small function replaces tokens in a string with values passed in as an associative array. Useful for creating small templates when something like Smarty is overkill or not available
Works great for quick form to email scripts.
Example:
Works great for quick form to email scripts.
<?php
function replaceTokens($tokenArr, $template)
{
while(list($token, $value) = each($tokenArr))
{
$template = str_replace("<%".$token."%>", $value, $template);
}
return $template;
}
Example:
$tokenArray = array();
$tokenArray['name'] = 'My Name';
$tokenArray['email'] = 'foo@bar.com';
$tokenArray['phone'] = '555-1212';
$template = <<<END
Name: <%name%>
Email: <%email%>
Phone: <%phone%>
END;
$parsed = replaceTokens($tokenArray, $template);
print $parsed;

