简体   繁体   中英

preg_replace regular expression outputs nothing

    $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;

Every instance of {text} turns out to be " " is there something I am doing wrong with the capture group? I did this with preg_match_all and it returns as {author} and author is this the issue being lead here?

In such case, you need preg_replace_callback :

$str = preg_replace_callback($pattern, function ($matches) use ($subst) {
    return $subst[$matches[1]];
}, $str);

Another solution is using strtr function:

// $subst needs to be changed a bit.
$subst= array('{author}'=>'Mr.Google','{id}'=>'1239124587123','{content}'=>'This is some simple text');
echo strtr($str, $subst);

The second parameter of preg_match_all is evaluated before the function runs. (Like all parameters always are.)

Enable proper error_reporting, and PHP will tell you: Notice: Undefined index: $1 in […]

You can not do it this way, because $1 will only reference what is captured, when the function has already found the matches – you will need to use preg_replace_callback instead:

$str = preg_replace_callback(
    $pattern,
    function($matches) use ($subst) {
        return $subst[$matches[1]];
    },
    $str
);

Edit: In case you can't use anonymous functions, this should work for 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]];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM