Link to home
Start Free TrialLog in
Avatar of jagguy
jagguyFlag for Australia

asked on

replace string template in php

Hi ,
In php I have a returned string as
$message='Enter message[phone][lastname][lastname][firstname]'

How do I replace the  [ ] with actual values like
$phone='424234' and needs to go where [phone] is;

  $phone='4444';
   str_replace('[phone]',$phone,$template) ;
'didnt work'
 and so the message will now have the data values inserted?
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here's an option using regular expression (preg_replace):

<?php
$message = 'Enter message [phone] [lastname] [firstname]';

$patterns = array(
	'/\[phone\]/',
	'/\[lastname\]/',
	'/\[firstname\]/'
);

$replacements = array(
	'123456',
	'stanyon',
	'chris'
);

echo preg_replace($patterns, $replacements, $message);

Open in new window

It looks like you're dealing with string data.  This is good background information:
http://php.net/manual/en/language.types.string.php#language.types.string.details

PHP has HEREDOC notation that is useful for templates.  Heed, but do not be put off by the warning on the man page.
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

To see how it works, follow the $name and $phone variables in this script.
http://iconoun.com/demo/temp_jagguy.php

<?php // demo/temp_jagguy.php

/**
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28618134.html
 */
ini_set('display_errors', TRUE);
ini_set('log_errors',     TRUE);
error_reporting(E_ALL);


// A DATA SET THAT WE NEED IN OUR OUTPUT STRING
$name  = 'JagGuy';
$phone = '424234';

// DEMONSTRATE THE USE OF HEREDOC TEMPLATES
$template = <<<EOD
<p>
This is a message to $name<br>
The phone $phone is here!
</p>
EOD;

// SHOW THE TEMPLATE WITH THE INCLUDED DATA SET
echo $template;

Open in new window