-1

I want replace php codes in string and running fro server

$x = 1;
$string = "OK:{first}Yes{second}No";

I want replace if($x == 1){ to {first} and } else { to {second}

After run and echo $string , I want result in html :

OK:Yes

Mohammad
  • 197
  • 3
  • 12

2 Answers2

4

How did you come up with this approach? Why not simply:

$string = $x == 1 ? 'OK:Yes' : 'OK:No';

That would get you the string you want based on the value of $x.

Also if you literally mean that you want to do a search-n-replace on the PHP code itself (as @OllyTenerife assumes), then are you going to write it into a file to be executed later, or use eval() or something? Doesn't sound like the right track there... In which case, remodel your code.

Markus AO
  • 4,771
  • 2
  • 18
  • 29
  • I want replce php code to string and run it ! , like blog templates – Mohammad May 28 '15 at 12:27
  • If you want to search-and-replace PHP code into a string, you're going to have to use `eval()` to then evaluate the code you've stored in that string. Using `eval()` is a very bad idea for a templating engine. You'd be better off just using e.g. `{result}` in your HTML, and then doing a search-replace over your HTML, where you replace `{result}` with the desired value. Use the code above, and then run `str_replace('{result}', $string, $HTMLcode);`, where $HTMLcode is your template file. – Markus AO May 28 '15 at 12:35
  • Otherwise, if you insist on having both options in your template string, you will have to use `preg_replace()` to accomplish your job -- and you will have to craft a bunch of regex patterns, assuming you have more than one token you intend to replace. In any case, trying to search-n-replace PHP code into a string for evaluation is not a good idea. – Markus AO May 28 '15 at 12:38
  • May be a good idea to get back to the drawing board and figure out what exactly you want to do in the big picture of what you're building. If this is just a one-off case, then you don't need templating. If you need basic templating with minimal code, have a look at my answer here: http://stackoverflow.com/questions/29838190/modify-php-customize-how-php-calls-a-function/29839101 – Markus AO May 28 '15 at 12:40
0
$string = str_replace("{first}","if($x == 1)",$string);
$string = str_replace("{second}","} else {",$string);
OllyBarca
  • 1,501
  • 1
  • 18
  • 35