Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Ignace Nyamagana Butera:
Regular expressions documented in PHP
Oct 20, 2015 @ 15:35:09

In this post to his site Ignace Nyamagana Butera shares a a helpful thing you can do with the regular expression handling in PHP to help make it a bit more clear: embedded comments.

One of the most challenging aspect of using regular expressions is documenting them. More than often you end up with a complex expression that even you as a creator have a hard time documenting. While reading sitepoint recent article around regular expressions I was intrigued that this article did not feature any tips on how to document them. So let’s take a very complex regular expression and see how we could improve its documentation.

He gives an example of a complex regular expression used to parse a URI into its different parts, including an example URI and the resulting parsed array. He points out that, while the regular expression works fine, it's easy to forget what each part does and as it is quite complex. To help remedy this, he includes an example of a commented regular expression (available since PHP 5.2) where you have two options:

  • add in named subpatterns with a special < and > notation
  • put in literal comments by breaking up the regex into multiple lines and using the hash (#) to mark of the comment at the end of the line

He includes code examples of both of these, resulting in a much clearer, memorable regular expression where the increased number of lines is a good trade-off for clarity.

tagged: regularexpression regex document comment named subpattern tutorial

Link: http://nyamsprod.com/blog/2015/regular-expressions-documented-in-php/


Trending Topics: