How to replace multiple% tags in a string using PHP

What is the best way to replace a set of short tags in a PHP string, for example:

$return = "Hello %name%, thank you for your interest in the %product_name%.  %representative_name% will contact you shortly!";

Where would I determine that% name% is a specific string, from an array or object, for example:

$object->name;
$object->product_name;

etc..

I know that I could run str_replace several times on a line, but I was wondering if there is a better way to do this.

Thank.

+3
source share
4 answers

str_replace () seems like the perfect option if you know the placeholders you are about to replace. This needs to be run only once several times.

$input = "Hello %name%, thank you for your interest in the %product_name%.  %representative_name% will contact you shortly!";

$output = str_replace(
    array('%name%', '%product_name%', '%representative_name%'),
    array($name, $productName, $representativeName),
    $input
);
+12
source

This class should do this:

<?php
class MyReplacer{
  function __construct($arr=array()){
    $this->arr=$arr;
  }

  private function replaceCallback($m){
    return isset($this->arr[$m[1]])?$this->arr[$m[1]]:'';
  }

  function get($s){  
    return preg_replace_callback('/%(.*?)%/',array(&$this,'replaceCallback'),$s);
  }

}


$rep= new MyReplacer(array(
    "name"=>"john",
    "age"=>"25"
  ));
$rep->arr['more']='!!!!!';  
echo $rep->get('Hello, %name%(%age%) %notset% %more%');
+2
source

- preg_replace 'e'

$obj = (object) array(
    'foo' => 'FOO',
    'bar' => 'BAR',
    'baz' => 'BAZ',
);

$str = "Hello %foo% and %bar% and %baz%";
echo preg_replace('~%(\w+)%~e', '$obj->$1', $str);
+2

PHP str_replace:

If the search and replace are arrays, then str_replace () takes a value from each array and uses them to search and replace with the topic. If the replacement has fewer values ​​than the search, then an empty string is used for the rest of the replacement value. If the search is array and replace is a string, then this replacement string is used for each search value. The converse does not make sense, however.

http://php.net/manual/en/function.str-replace.php

+1
source

Source: https://habr.com/ru/post/1752993/


All Articles