Re: how to conver a string to float
| From: | André Cerqueira | Date: | Sun, 08 Feb 2004 07:20:24 +0000 |
| Subject: | Re: how to conver a string to float | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-177170@lists.php.net to get a copy of this message | ||
Sebastian wrote:
Is there a possibility to convert a string like "10*500" (parsed from a XML-File) to a float? When i try to store this String in a float variable it only coverts the "10" but nothing after the "*"-sign, but i need the result of this expresison... Is there a function to calculate such string expressions? Thanx...Using eval() can be dangerous If the source of the xml data is not trustworthy, validate the string with regex before eval()'ing it /^[^a-zA-Z]*$/ should be enough... That would refuse letters (simple (and maybe dumb) way to prevent function execution (but wouldnt prevent expression errors! just prevent people from breaking in through your eval!)) Note: you would also need to put 'return ' before and ';' after the string expression to eval ex: <? $expression = '10*500'; $expressionOK = preg_match ('/^[^A-Za-z]*$/', $expression); $result = ($expressionOK) ? eval('return '. $expression .';') : NULL; var_dump($result); ?> Another more complex/slower, but maybe safer/elegant way, would be to parse the expression, piece by piece into a stack, and do the operations yourself