1

Apologies for the poor title and explanation.

Say I have an array like this:

$myArray = array(
    "name" => "Hello",
    "description" => "World"
);

and some HTML like this:

<h1>{name}</h1>
<p>{description}</p>

Using PHP's preg_replace function (or something else, I don't mind), would it be possible to replace the {} strings with the value in the array?

<h1>Hello</h1>
<p>World</p>
4
  • Yes, it is possible with preg_replace_callback. I'm sure some kind soul will give you codez in a minute. Commented Feb 8, 2015 at 16:05
  • I don't think using regex for this would be the smartest choice, would could fairly easily write a function that parses text and places instances of keys from a map though, i think that would be the way to go, personally. Commented Feb 8, 2015 at 16:05
  • @will The proposed function would parse text automagically? Without regexps? Commented Feb 8, 2015 at 16:13
  • @mudasobwa Not automatically, no, but using regex seems to be overkill to me. If you know it's always going to be enclosed in {}, and you never have a { or } in the key, then you only need to scan through the text once building a list of indicies for substring replacements. It's probably due to not really using php, and a habit from other experiences, but i don't like using regex for every possible oportunity - seems overkill. I do like the ouzo-goodies solution below though, which has abstracted away the not so nice expression above. Commented Feb 8, 2015 at 22:15

2 Answers 2

2

You can do this in vanilla PHP like this:

$str = '<h1>{name}</h1>
<p>{description}</p>';

$myArray = array(
    "name" => "Hello",
    "description" => "World"
);

echo preg_replace_callback('/\{(\w+)}/', function($match) use ($myArray){
    $matched = $match[0];
    $name = $match[1];
    return isset($myArray[$name]) ? $myArray[$name] : $matched;
}, $str);

And here is the result:

<h1>Hello</h1>
<p>World</p>

Or you can use e.g. ouzo-goodies which implements StrSubstitutor

$str = '<h1>{{name}}</h1>
<p>{{description}}</p>';

$myArray = array(
    "name" => "Hello",
    "description" => "World"
);

$strSubstitutor = new StrSubstitutor($myArray);
$substituted = $strSubstitutor->replace($str);
Sign up to request clarification or add additional context in comments.

Comments

0

First, let’s construct the regular expression:

$re = implode('|', array_map(function($el) { 
                     return '{' . $el . '}'; 
                   }, array_keys($myArray));

Now we are ready to rock:

$result = preg_replace_callback(
  "/$re/", 
  function($match) use($myArray) { 
    return $myArray[$match[0]]; 
  } , $input
);

Comments