2

The expression is for calculating the form of a plural string for Gettext. Example:

$expr = 'n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2';

with eval I'm doing something like:

$expr = str_replace('n','$n', $expr); $n = 5; $result = (int)eval("return $expr;"); 

Can this be done without eval too?

3
  • May I ask why you want to do it without eval? I'm afraid that it would be quite tricky. If it is for the security reasons that eval might cause, then the easiest solution is probably to create a script that parses the entered text and then makes sure it is safe before passing it on. Commented Feb 26, 2012 at 23:32
  • 2
    Can't you leave it to the Gettext library, as in the original .po file this plural is given in the header? (I have no experience with the PHP implementation.) Maybe the plural declaration in the .po is missing? php.net/manual/en/function.dngettext.php Commented Feb 26, 2012 at 23:33
  • thanks, i had no idea php had that :) Commented Feb 26, 2012 at 23:38

1 Answer 1

3

Even though it is possible to build a parser that would be able to parse limited amount (you need only trivial math operators to calculate plurals) it doesn't worth it in terms of time you spend implementing it and performance (obviously it will be slower).

So I'd personally go with eval() or just implement a function per language you need to pluralize.

It is one of the cases when I assume eval as not "evil" as long as its input is predefined by you

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

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.