Writing better regular expressions in PHP

Click for: original source

Regular Expressions are powerful, PHP but they are not known to be readable, and more often than not, maintaining a regular expression is not a straight-forward task. By Ayesh Karunaratne.

Further, using these improvements also means the regular expressions might be less portable to other languages. For example, named captures are supported even in older PHP versions, but in JavaScript, named captures feature was only added in ECMAScript 2018.

The choice of the delimiter is important because all occurrences of the delimiter character within the expression must be escaped. The fewer escaped characters inside a regular expression, the more readable it will be. Not choosing meta characters (such as ^, $, braces, and other characters that carry special meaning in regular expressions) can reduce the number of characters escaped.

The article brings information on the following:

  • Choice of delimiter
  • Reducing escape characters
  • Non-capture groups
  • Named captures
  • Using comments
  • Named character classes

Regular expressions support character classes, and they can help take the scrutiny off a regular expression while making them more readable at the same time. Good read!

[Read More]

Tags php web-development app-development programming