我会鼓励preg_replace_callback
。通过使用这种方法,我们可以轻松地使用捕获的值作为查找来确定它们的替换应该是什么。如果我们遇到无效的密钥,可能是拼写错误的原因,我们也可以对此做出回应。
// This will be called for every match ( $m represents the match )
function replacer ( $m ) {
// Construct our array of replacements
$data = array( "price" => 5, "demand" => "low" );
// Return the proper value, or indicate key was invalid
return isset( $data[ $m[1] ] ) ? $data[ $m[1] ] : "{invalid key}" ;
}
// Our main widget function which takes a string with placeholders
function widget ( $arguments ) {
// Performs a lookup on anything between { and }
echo preg_replace_callback( "/{(.+?)}/", 'replacer', $arguments );
}
// The price is 5 and {invalid key} demand is low.
widget( "The price is {price} and {nothing} demand is {demand}." );
演示:http ://codepad.org/9HvmQA6T