2

I need to read an string to find variables (tags) and replace it with stored values. I used % (percent) to identify the tags. The input should accept some tags like %color% and %animal%, so with PHP I need to insert the real string... Better explained with codes:

// We have some strings stored
$color = 'white';
$animal = 'cat';

The user should use %color%, %animal%, or nothing in the textarea to show the variable he want.

// The user text was stored by the $text
$text = "The quick %color% fox jumps over the lazy %animal%.";

The %color% and the %animal% of the $text should be replaced by the $color and the $animal values. But, how can I do it? The final output should be

<p>The quick white fox jumps over the lazy cat.</p>

WordPress allow the users to do this in the "permalink" options, so the users can set, for example, the following extructure:

http://localhost/site/%category%/%postname%/
  • Welcome to SO, it would make it easier if your inputs comes in an array rather than individual variables. You can pass the array to `str_replace` – DevZer0 Jul 26 '13 at 03:52
  • http://stackoverflow.com/questions/3158743/simple-template-var-replacement-but-with-a-twist – teynon Jul 26 '13 at 04:04

3 Answers3

1

You can try

$text = str_replace("%color%", $color, $text );
$text = str_replace("%animal%", $animal, $text );
1

Using the php printf function

 $color = 'red';
 $animal = 'cat';
 printf("The quick %s fox jumps over the lazy %s",$color,$animal);
elzaer
  • 729
  • 7
  • 25
0

If you trust your input use preg_replace:

$color = 'white';
$animal = 'cat';
$text = "The quick %color% fox jumps over the lazy %animal%.";

$result = preg_replace('/\%([a-z]+)\%/e', "$$1", $text);

This means that any lower case characters from a-z between % characters will be replaced with the PHP variable of that name. If you don't trust your input this is a massive security risk though and you should do some kind of checking to make sure those variables are allowed to be accessed.

str_replace solution:

$color = 'white';
$animal = 'cat';
$text = "The quick %color% fox jumps over the lazy %animal%.";
$vars = array("color","animal");

foreach ($vars as $var) {
$text = str_replace("%{$var}%",$$var,$text);
}
echo $text;

Just to explain further for anyone who hasn't used it before double dollar sign ($$) indicates a variable variable: http://php.net/manual/en/language.variables.variable.php

Jay Rafferty
  • 630
  • 5
  • 9
  • http://stackoverflow.com/a/3763835/2619379 is a good solution if you don't trust the input - you can define an array of allowed/whitelisted variables. – Jay Rafferty Jul 26 '13 at 04:04