0

I'm trying to create function which accepts a string (contains simple math expression) then splits each of the parts as an array.

For example the input is 2 + 3 * 7 or 2 – 5 / 3.4, the output should be like ["2", "+", "3", "*", "7"] and ["2", "-", "5", "/", "3.4"]

Here are my codes:

$input = "2 + 3 * 7";
$input = "2-5/3.4";

function splitExpression($string) {
    $result = explode (" ", $input);
    print_r ($result);
}

Using only explode, of course the 1st example works nicely, but not the same with the other.

Mojtaba Ahmadi
  • 1,044
  • 19
  • 38
marcato21
  • 3
  • 3
  • 1
    Possible duplicate of [Trying to split a string in 3 variables, but a little more tricky - PHP](https://stackoverflow.com/questions/4382163/trying-to-split-a-string-in-3-variables-but-a-little-more-tricky-php) – Alperen Kantarcı Apr 30 '19 at 06:30

3 Answers3

2

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
)
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
1

you can use a regex:

$matches = array();
$input="2 + 3 * 7 / 5 - 3";
preg_match_all("/\d+|[\\+\\-\\/\\*]/",$input,$matches);

this regex searches for a number or an operator and puts the matches into $matches. you can edit the design of the matches array by flags.

matches:
 + 0
     - 0 : 2
     - 1 : +
     - 2 : 3
     - 3 : *
     - 4 : 7
     - 5 : /
     - 6 : 5
     - 7 : -
     - 8 : 3
TheBlueOne
  • 486
  • 5
  • 13
-1

You can use str_split() for it. Like str_split($str1);

$input = "2-5/3.4";
$input = "2 + 3 * 7";

function splitExpression($string) {
    //$result = str_split (string);
    $result = str_split (preg_replace('/\s+/', '', $string));
    return $result;
}
$arr1 = splitExpression($input);

Where preg_replace('/\s+/', '', $string) used to remove white space from string.

Qirel
  • 25,449
  • 7
  • 45
  • 62
Shehroz Altaf
  • 618
  • 1
  • 10
  • 17
  • What if the string is `30 + 4 *2`? Or `40+3.4`? Or the first of the `$input`? This doesn't really work. This will only work when there are integers, no decimals, and no number greater than 9. Quite the heavy restriction. – Qirel Apr 30 '19 at 06:46