1

I want to replace values in a string if a particular string exists in an array.

$str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';

$array = array(
    'name' => '010 Pixel',
    'city' => 'USA',
    'hobby' => 'code',
    'email' => 'xyz@abc.com'
);

I want to replace {{name}} with the value of name in $array. If the string inside curly brackets doesn't exist in the $array then let that string stay as it is.

Expected result:

My name is 010 Pixel. I live in USA. I love to code. {{ops...}}

The reason I'm concern about this is, when any value coming from form contains any {{field-name}} then it shouldn't get replaced. I want to replace only what is set in $str.

010 Pixel
  • 195
  • 3
  • 14
  • 1
    This is why I like StackOverflow, here we have working 4 answers with all different approaches ! – Birla Feb 25 '14 at 09:46

5 Answers5

3

There is strtr function.

$str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';

$array = array(
    '{{name}}' => '010 Pixel',
    '{{city}}' => 'USA',
    '{{hobby}}' => 'code',
    '{{email}}' => 'xyz@abc.com'
);
echo strtr($str, $array);
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Try this:

<?
$str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';

$array = array(
    'name' => '010 Pixel',
    'city' => 'USA',
    'hobby' => 'code',
    'email' => 'xyz@abc.com'
);

if (preg_match_all("/{{(.*?)}}/", $str, $m)) {
  foreach ($m[1] as $i => $varname) {
    $str = str_replace($m[0][$i], $array[$varname], $str);
  }
}
Birla
  • 1,170
  • 11
  • 30
1
$str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';

$array = array(
    'name' => '010 Pixel',
    'city' => 'USA',
    'hobby' => 'code',
    'email' => 'xyz@abc.com'
);

$callback = function($match) use ($array) {
    if (array_key_exists($match[1], $array)) {
        return $array[$match[1]];
    } else {
        return $match[0];
    }
};

$str = preg_replace_callback('/\{\{(.*?)\}\}/', $callback, $str);
gontrollez
  • 6,372
  • 2
  • 28
  • 36
1

Using preg_replace_callback works-

$str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';
$array = array(
    'name' => '010 Pixel',
    'city' => 'USA',
    'hobby' => 'code',
    'email' => 'xyz@abc.com'
);
$res = preg_replace_callback('/\{{2}(.*?)\}{2}/',
        function($matches)use($array){
            $key = $matches[1];
            if(isset($array[$key])){
                return "{{".$array[$key]."}}";
            };
            return $matches[0];
        },
        $str);
var_dump($res);
/*
    OUTPUT-
    string 'My name is {{010 Pixel}}. I live in {{USA}}. I love to {{code}}. {{ops...}}' (length=75)
*/
Kamehameha
  • 5,423
  • 1
  • 23
  • 28
0
$string = preg_replace('/{{([a-zA-Z\_\-]*?)}}/ie','$array',$str);

Hope this could help

SpencerX
  • 5,453
  • 1
  • 14
  • 21