PHP - Check if string is a formula

From Global Programming Syntax

Jump to: navigation, search

Sometimes when storing mathematical data, you may need to sort the formulas from the strings. This function will allow you to add the formula into the function and the function will return 'true' if it is a formula or 'false' if it is just a number or string. So to use it, first copy the below code box into your php file (preferably near the top).

<?
function check_if_formula($val)
{
while (preg_replace('/(\ |\ )?(.*[^\ \ ])(\ |\ )?/is','$2',$val)!==$val)
{
$val=preg_replace('/(\ |\ )?(.*[^\ \ ])(\ |\ )?/is','$2',$val);
}
 
if (preg_match('/(\*|\/|\+|\-|\)|\(|\ |\ )/is',$val)!==0)
{
if (preg_match('/[a-zA-Z]/is',$val)!==0)
{
return 'false';
} else {
return 'true';
}
} else {
return 'false';
}
}
?>

Then to call this function just use the following command line except place your own formula within the quotes.

check_if_formula('1056*5/ 65'); //returns true since this is a formula.

And of course you could use the following to display the result:

echo check_if_formula('1056*5/ 65');
Personal tools
languages
page stats
Toolbox