如何使用正则表达式检测 PHP 上数学运算符上的所有符号?

问题描述 投票:0回答:1

如何使用正则表达式检测 PHP 上数学运算符上的所有符号?

示例:

$operators = [">0",">=1","==12","<9","<=1","!=4"];
$results = array();
foreach ($operators as $key => $value){
  detect $value using regex, if include symbol of maths operators {
    array_push($results, $value);
    // just push $value with format of symbol of maths operators, example : ">" // remove 0 on my string
  }
}

从我的数组中,我只想收集数学运算符。这是我的预期结果:

$results = [">",">=","==","<","<=","!="];

我该怎么做?

php regex string operators
1个回答
1
投票

您可以简单地将

array_map
preg_replace
一起使用,如 as

$operators = [">0", ">=1", "==12", "<9", "<=1", "!=4"];
print_r(array_map(function($v) {
            return preg_replace('/[^\D]/', '', $v);
        }, $operators));

输出:

Array
(
    [0] => >
    [1] => >=
    [2] => ==
    [3] => <
    [4] => <=
    [5] => !=
)

演示

© www.soinside.com 2019 - 2024. All rights reserved.