tags:

views:

44

answers:

3

I have a paragraph of text like:

$paragraph = "Hello there {Customer.name}, You are {Customer.age} years old. You were born in the year {Customer.birthdate}";

I want to replace this with contents of an array such as

array('Customer' => array('name'=>'Tom', 'age'=>8, 'birthdate'=>'1980-01-01'))

My question is what is the best way to go about doing this? If you have a suggestion on how to format the text that would also be helpful. I am guessing you would have to use some kind of regular expression, maybe preg_filter or preg_replace.

+2  A: 

http://php.net/manual/en/function.sprintf.php

$format_string = "Hello there %s, You are %d years old. You were born in the year %s";
$paragraph = sprintf($format_string, 
                     $customer['name'], 
                     $customer['age'], 
                     $customer['birthdate']);
echo
+2  A: 

You'll want to use preg_replace_callback() for this. Just match on \{(.+)\.(.+)\} and index the array appropriately.

Ignacio Vazquez-Abrams
You might need to escape the braces.
Max Shawabkeh
@Max: Right, good catch.
Ignacio Vazquez-Abrams
I'm trying to work this out now. Could you give me some sample code to help me start?
jimiyash
`function fill_array($matches)``{`` if(!isset($myarray[$matches[0]]) || !isset($myarray[$matches[0]][$matches[1]]))`` {`` return "{$matches[0].$matches[1]}";`` }`` return $myarray[$matches[0]][$matches[1]];``}`
Ignacio Vazquez-Abrams
The `0`s and `1`s in the previous snippet should be `1` and `2` respectively.
Ignacio Vazquez-Abrams
A: 

If the format of the sentence in $paragraph will always be consistent with the curly brace syntax, you could use str_replace().

Jansen Price