I am trying to extract only operands viz. + - /
and *
from my arithmetic expression.
E.g.: A + B
should return me +
I tried using following few RegEx but I always get an array with 3 elements:
Expression #1:
print_r (var_dump(preg_split ( "/([\w\s]*[^\-\+\/\*])/", "A+B" )), TRUE);
Output:
array(3) {
[0] =>
string(0) ""
[1] =>
string(1) "+"
[2] =>
string(0) ""
}
Expression #2:
print_r (var_dump(preg_split ( "/(?!\+|\-|\*|\/)[\w\s]+/", "A+B" )), TRUE);
Output:
array(3) {
[0] =>
string(0) ""
[1] =>
string(1) "+"
[2] =>
string(0) ""
}
I just want a +
sign as output.
Any clue what am I doing wrong?
As Wiktor said you'd better use preg_match, but if you really want to use preg_split use the flag PREG_SPLIT_NO_EMPTY
and simplify your regex:
print_r (var_dump(preg_split ( "/[\w\s]/", "A+B", -1, PREG_SPLIT_NO_EMPTY )), TRUE);
Output:
array(1) {
[0]=>
string(1) "+"
}
You can use preg_match_all :
preg_match_all ( "/([\^\-\+\/\*])/", "A+B", $result );
$result = $result[0];
print_r($result);
The result is :
Array ( [0] => + )