简体   繁体   中英

PHP Preg_replace placeholders

Hi I'm writing something for handling my views an I need a preg_replace here, but i can't seem to get it working so I've scrapped the code.

the strings I am trying to replace are dynamic based on a template, eg

{{name}} is {{age}} years old

And the passed information into the function is an array eg

array( 'name' => 'John Doe', 'age' => '27' );

The pattern I have so far is \\{{([a-zA-Z0-9]+)\\}} however this only seems to match one pair of braces.

I'm also having a problem looping through results in preg_match_all..

Thanks in advance

...however this only seems to match one pair of braces.

You forgot the escape the second {

/\{\{([a-zA-Z0-9]+)\}\}/
  -^-               -^-

In any case, try this regex, it's a bit shorter:

/\{\{([^}]+)\}\}/

preg_replace_callback seems like a good candidate.

$str = "{{name}} is {{age}} years old";
$values = array( 'name' => 'John Doe', 'age' => '27' );
echo preg_replace_callback("/\{{([a-z0-9]+?)\}}/i", function ($result)
use ($values) {
   if (isset($result[1])) {
      return $values[$result[1]];
   }
}, $str);

The main issue is that {{[az]+}} will match from {{name ... age}} . Using the ? makes the + reluctant so it only matches up to the first } rather than the last.

Why don't you use sprintf ?

$template = '%s is %d years old';
$vars = array('name' => 'John Doe', 'age' => 27);
$output = sprintf($template, $vars['name'], $vars['age']);

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