Regex to split string into array of numbers and characters using PHP

拟墨画扇 提交于 2019-12-13 11:18:12

问题


I have an arithmetic string that will be similar to the following pattern.

a. 1+2+3
b. 2/1*100
c. 1+2+3/3*100
d. (1*2)/(3*4)*100

Points to note are that
1. the string will never contain spaces.
2. the string will always be a combination of Numbers, Arithmetic symbols (+, -, *, /) and the characters '(' and ')'

I am looking for a regex in PHP to split the characters based on their type and form an array of individual string characters like below.
(Note: I cannot use str_split because I want numbers greater than 10 to not to be split.)

a. 1+2+3
output => [
0 => '1'
1 => '+'
2 => '2'
3 => '+'
4 => '3'
]

b. 2/1*100
output => [
0 => '2'
1 => '/'
2 => '1'
3 => '*'
4 => '100'
]`

c. 1+2+3/3*100

output => [
0 => '1'
1 => '+'
2 => '2'
3 => '+'
4 => '3'
5 => '/'
6 => '3'
7 => '*'
8 => '100'
]`

d. (1*2)/(3*4)*100

output => [
0 => '('
1 => '1'
2 => '*'
3 => '2'
4 => ')'
5 => '/'
6 => '('
7 => '3'
8 => '*'
9 => '4'
10 => ')'
11 => '*'
12 => '100'
]

Thank you very much in advance.


回答1:


Use this regex :
(?<=[()\/*+-])(?=[0-9()])|(?<=[0-9()])(?=[()\/*+-])

It will match every position between a digit or a parenthesis and a operator or a parenthesis.
(?<=[()\/*+-])(?=[0-9()]) matches the position with a parenthesis or an operator at the left and a digit or parenthesis at the right
(?<=[0-9()])(?=[()\/*+-]) is the same but with left and right reversed.

Demo here




回答2:


Since you state that the expressions are "clean", no spaces or such, you could split on

\b|(?<=\W)(?=\W)

It splits on all word boundaries and boundaries between non word characters (using positive lookarounds matching a position between two non word characters).

See an illustration here at regex101




回答3:


As I said, I will help you with that if you can provide some work you did by yourself to solve that problem.

However, if when crafting an unidimensional array out of an arithmetic expression, your objective is to parse and cimpute that array, then you should build a tree instead and hierarchise it by putting the operators as nodes, the branches being the operands :

'(1*2)/(3*4)*100'

Array
(
    [operand] => '*',
    [left] => Array
        (
            [operand] => '/',
            [left] => Array
                (
                    [operand] => '*',
                    [left] => 1,
                    [right] => 2
                ),
            [right] => Array
                (
                    [operand] => '*',
                    [left] => 3,
                    [right] => 4
                )
        ),
    [right] => 100
)



回答4:


There is no need to use regex for this. You just loop through the string and build the array as you want.

Edit, just realized it can be done much faster with a while loop instead of two for loops and if().

$str ="(10*2)/(3*40)*100";
$str = str_split($str); // make str an array

$arr = array();
$j=0; // counter for new array
for($i=0;$i<count($str);$i++){ 
    if(is_numeric($str[$i])){ // if the item is a number
        $arr[$j] = $str[$i]; // add it to new array 
        $k = $i+1;
        while(is_numeric($str[$k])){ // while it's still a number append to new array item.
            $arr[$j] .= $str[$k]; 
            $k++; // add one to counter.
            if($k == count($str)) break; // if counter is out of bounds, break loop.
        }
        $j++; // we are done with this item, add one to counter.
        $i=$k-1; // set new value to $i
    }else{
        // not number, add it to the new array and add one to array counter.
        $arr[$j] = $str[$i]; 
        $j++;
    }
}

var_dump($arr);

https://3v4l.org/p9jZp




回答5:


You can also use this matching regex: [()+\-*\/]|\d+

Demo




回答6:


I was doing something similar to this for a php calculator demo. A related post.

Consider this pattern for preg_split():

~-?\d+|[()*/+-]~ (Pattern Demo)

This has the added benefit of allowing negative numbers without confusing them for operators. The first "alternative" matches positive or negative integers, while the second "alternative (after the |) matches parentheses and operators -- one at a time.

In the php implementation, I place the entire pattern in a capture group and retain the delimiters. This way no substrings are left behind. ~ is used as the pattern delimiter so that the slash in the pattern doesn't need to be escaped.

Code: (Demo)

$expression='(1*2)/(3*4)*100+-10';
var_export(preg_split('~(-?\d+|[()*/+-])~',$expression,NULL,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE));

Output:

array (
  0 => '(',
  1 => '1',
  2 => '*',
  3 => '2',
  4 => ')',
  5 => '/',
  6 => '(',
  7 => '3',
  8 => '*',
  9 => '4',
  10 => ')',
  11 => '*',
  12 => '100',
  13 => '+',
  14 => '-10',
)


来源:https://stackoverflow.com/questions/45607486/regex-to-split-string-into-array-of-numbers-and-characters-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!