kukko kukko - 4 months ago 12
PHP Question

Regular expression match multiple substring

I have written a regular expression to test how a string is a logical expression or not. Here is the regular expression:

/(.*)(<|>|<=|>=|=|!=)(.*)/


And here is the subject which I tested with the expression above:

3!=2


The
preg_match_all
function in PHP return the following array:

[
[
"3!=2"
],
[
null
],
[
"="
],
[
"2"
]
]


I got a wrong logical operator because it's not match only the
=
pattern but also match the
!=
operator. How should I rewrite the regular expression to not match multiple strings in the brackets?

Answer

You should exclude <>! before the operator and = after operator. Then, just to shorten, group the operators tighter.

([^<>!]*)([<>]=?|!?=)([^=]*)

You could also shorten it a bit with this:

(\w+)([<>]=?|!?=)(\w+)

With <=>, use

([^<>!]*)(<=>|[<>]=?|!?=)([^=>]*)

or, better yet in some cases,

(\w+)(<=>|[<>]=?|!?=)(\w+)
Comments