The main purpose of regular expressions, also called regex or regexp, is to efficiently search for patterns in a given text. These search patterns are written using a special format which a regular expression parser understands.
Regular expressions are originating from Unix systems, where a program was designed, called grep, to help users work with strings and manipulate text. By following a few basic rules, one can create very complex search patterns.
In this tutorial we will create a PHP URL router. The developer using the router will be able to define these routes with regular expressions, these will then map to a file, class and method which will be called – very similar to Django’s routing. By using regular expressions to define our URLs we get maximum customizability. /class/method/ based URL routing is too restrictive sometimes. We will assume the user is using an apache or similar web server with mod_rewite enabled. You can adapt this router and use it in your web application or framework.
Regular Expressions are the Swiss Army knife for searching through information for certain patterns. They have a wide arsenal of tools, some of which often go undiscovered or underutilized. Today I will show you some advanced tips for working with regular expressions.