PHP use string as operator
You can use eval()
as suggested by @konforce, however the safest route would be something like:
$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){
case "*":
$result = $left * $right;
break;
case "+";
$result = $left + $right;
break;
// etc
}
PHP - arithmetic operations using strings as operators
trickery with math:
echo $initial + (($operation == '-') ? -1 : 1) * $unit;
only using addition, but cheating with multiplying by a negative... :)
can we convert a string into a sign in php
You should do an if statement or a switch case one;
example
if ($opt =='+'){
return $val1+$val2;
}else if($opt =='-'){
return $val1-$val2;
} .... etc
How can I use the += operator in PHP for a string?
You are searching for .=
:
$str = "";
$str .= "some value";
How to split some numbers and math operator in PHP?
You can try like this - based upon answer elsewhere on stack. Modified the pattern and added the preg_replace so that the results are not affected by spaces in the input string.
$input = '2 + 3 * 7';
$input = '2-5/3.4';
$pttn='@([-/+\*])@';
$out=preg_split( $pttn, preg_replace( '@\s@', '', $input ), -1, PREG_SPLIT_DELIM_CAPTURE );
printf('<pre>%s</pre>',print_r( $out, true ) );
Will output:
Array
(
[0] => 2
[1] => -
[2] => 5
[3] => /
[4] => 3.4
)
Update:
$input = '2 + 5 - 4 / 2.6';
$pttn='+-/*'; # standard mathematical operators
$pttn=sprintf( '@([%s])@', preg_quote( $pttn ) ); # an escaped/quoted pattern
$out=preg_split( $pttn, preg_replace( '@\s@', '', $input ), -1, PREG_SPLIT_DELIM_CAPTURE );
printf('<pre>%s</pre>',print_r( $out, true ) );
outputs:
Array
(
[0] => 2
[1] => +
[2] => 5
[3] => -
[4] => 4
[5] => /
[6] => 2.6
)
Related Topics
File_Get_Contents Returns Empty String
Why Does File_Get_Contents Work with Google.Com But Not with My Site
Download of .Zip File Runs a Corrupted File PHP
Populate Select Drop Down from a Database Table
PHP - Sort Multi-Dimensional Array by Another Array
Php: Session Lost on Subdomain
How to Find Timezone Id from Ip Address/Country Name in PHP
Remove First 4 Characters of a String with PHP
Pcre Regular Expression Overlapping Matches
How to Send an HTML Email with an Inline Attached Image with PHP
Why Can't I Access the Array with Index Directly
How to Remove <Br /> Tags and More from a String
Call to Undefined Function MySQLi_Result::Num_Rows()
Mail(): Smtp Server Response: 550 the Address Is Not Valid Error on Hmailserver