Preg_replace regex doesn't display anything
$str = '<div class="hello">{author}</div><div id="post_{id}"><div class="content">{content}</div></div>';
$pattern = '/\{([a-z _0-9]+)\}/i';
$subst= array('author'=>'Mr.Google','id'=>'1239124587123','content'=>'This is some simple text');
$str = preg_replace($pattern,$subst['$1'],$str);
echo $str;
Each instance {text}turns out to be " ", is there something I am doing wrong with the capture group? I did this with help preg_match_all, and it comes back like {author}that author. Is this the problem here?
+4
2 answers
In this case, you need preg_replace_callback :
$str = preg_replace_callback($pattern, function ($matches) use ($subst) {
return $subst[$matches[1]];
}, $str);
Another solution uses strtr :
// $subst needs to be changed a bit.
$subst= array('{author}'=>'Mr.Google','{id}'=>'1239124587123','{content}'=>'This is some simple text');
echo strtr($str, $subst);
+3
The second parameter preg_match_allis evaluated before the function starts. (Like all options, there are always.)
error_reporting, PHP : : Undefined index: $1 [...]
, $1 , , - preg_replace_callback:
$str = preg_replace_callback(
$pattern,
function($matches) use ($subst) {
return $subst[$matches[1]];
},
$str
);
: , PHP < 5.3.0:
$str = preg_replace_callback($pattern, 'my_custom_replacement_function', $str);
function my_custom_replacement_function($matches) {
global $subst;
return $subst[$matches[1]];
}
+1