-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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I want replce php code to string and run it ! , like blog templates
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.
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.
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: stackoverflow.com/questions/29838190/…
0
$string = str_replace("{first}","if($x == 1)",$string);
$string = str_replace("{second}","} else {",$string);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.