php正则表达式在字符串中查找符号


php regex find symbols in a string

如何在字符串中

-1 -2 -3 -4

获取

array(-1, -2, -3, -4)

使用正则表达式和函数

preg_match_all

感谢您的帮助!谢谢

使用此:

/(([-]?'d+))/gmi

结果:

MATCH 1
1.  [1-3]   `-1`
MATCH 2
1.  [8-10]  `-2`
MATCH 3
1.  [15-17] `-3`
MATCH 4
1.  [22-24] `-4`

参见演示

在PHP使用中:

  $string = '(-1) * (-2) - (-3) * (-4)';
  $regex = '/(([-]?'d+))/i';
  preg_match_all($regex, $string, $matches);
  print_r($matches[1]);

结果:

Array ( [0] => -1 [1] => -2 [2] => -3 [3] => -4 )