Skip to content
Advertisement

Replace placeholders in text by referencing a translation variable

I’m trying to remove eval from the following function. I tried with sprintf and ${} , but still cannot find a solution.

Here the function:

JavaScript

Advertisement

Answer

So, yes, eval() is often detested as one of the highest order “evils” in php. In most cases, when a task lends itself to be solved by eval() or variable-variables (which are basically poorly packaged arrays), this is a symptom of inappropriately stored/declared data and often the best course of action is a complete rethink.

To solve your isolated question without fundamentally rewriting the custom function, I’ll offer a lesser “evil” (but still an “evil” in my opinion because there are risks in its usage) — GLOBALS & global

Code: (Demo)

JavaScript

Output:

JavaScript

…so why is this workaround a “bad idea”, well, imagine you have a string that contains {{ $db }} — such a common variable name is likely to exists in your list of global variables. So if the {{ variable }} in your string matches ANY of the variables in the global scope, you’re going to get faulty outcomes.


Now, what should you do? Just declare your $pippo data in an array so that you have an associative relationship to leverage. (Demo)

JavaScript

Depending upon the amount of control you have over your input data, you can now afford to remove the $ before pippo in your input string — which eliminates a few unnecessary characters here and there.

And if you are still reading, you can clean this whole thing up with strtr() or str_replace(). (Demo)

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement