Regular expressions are usually hard to read and understand. Even if you have a lot of experience on the subject, when you retakeone that you wrote some time ago, it is difficult to catch up.
Some days ago, a very smart guy at work named Zoltán recommended us to write complex regular expressions sepparating each logical part in a different line and also comment every one.
I did not know that this was possible at all, but he shown us how the modifier "x" (see it at the end of the following example) makes the compiler to ignore any whitespaces (spaces, tabs, line breaks) and even comments!!
So, with this, you can write crazy regular expressions easy to parse and understand. Here there is a silly example, imagine it in a single line!:
if ( preg_match('/
^ # We match the beginning because we match full string.
(Can|May)\x20 # May is more formal, can Can is also OK.
[yY]ou\s # You can match space with backslash and space or any whitespace with \s
(please)?\x20 # "Please" is optional ;)
(comment|document)\x20 # Commenting = documenting
this\ regexp\x20 # If UNICODE mode is on (modifier "u"), you can also match space with \x20
to\s(know|see)\x20
(what|WTF)\x20 # WTF = World Taekwondo Federation
it\ does\? # Note the "x" modificator int he next line. If makes regexp ignore whitespaces.
$ # We match the end because we match full string.
/x',
"Can you please comment this regexp to know what it does?" ) )
{
echo "Thank you!";
}
Thank you Zoly!
Leave your comment Writing complex regular expressions
Log in to Obolog, or create your free blog if you are not registered yet.