monoy suronoy
monoy suronoy

Reputation: 911

How can I detect all symbols on mathematical operators on PHP using regex?

How can I detect all symbols on mathematical operators on PHP using regex?

Example:

$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
  }
}

From my array I want to collect just math operators. Here is my expected results:

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

How can I do that?

Upvotes: -3

Views: 196

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

You can simply use array_map along with preg_replace like as

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

Output:

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

Demo

Upvotes: 1

Related Questions