Monday, 25 December, 2017 UTC


This blog has been about JavaScript so far. However, with the topic of regular expressions, we are diving in more deep waters. As a refresher, some other languages will also surface on our horizon. In this post, we will get started with writing and testing simple regular expressions in PHP. Don’t worry if you don’t have PHP installed on your machine, we will simply execute our code in an online environment accessible from the browser.
Both PHP and JavaScript regular expressions are based on the PCRE dialect as well as the Regex execution environments of most programming languages. Our goal here is not a comprehensive overview, but a brief tutorial on getting started with regular expressions in PHP.
When you want a quick solution for generating code for matching regular expressions, head over to the code generator of
PHP offers global functions to handle regular expressions. These start with:
  • preg_ matching the Perl PCRE syntax,
  • ereg_ based on the ERE dialect,
  • mb_ereg also based on the ERE dialect, with the ability of handling Unicode characters.
We will only deal with the PCRE syntax here.
In PHP, some modifiers are the same as in JavaScript, while others are different:
  • i stands for case-insensitivity just like in JavaScript,
  • m stands for multiline just like in JavaScript,
  • u stands for Unicode matching just like in JavaScript,
  • s makes the . character match all characters without exception
  • x turns on free spacing mode for easier readability. Free spacing mode ignores whitespace characters between regex characters
Consult the PCRE section of the PHP manual for the documentation of all PCRE regex functions.
You can execute PHP code online using many sandbox solutions such as or the Joodle PHP online editor.
We can use preg_match to return the first match from a string.
preg_match('/xy+/', 'xyxyyxyyy', $matches, PREG_OFFSET_CAPTURE);
The result is:
Array ( [0] => Array ( [0] => xy [1] => 0 ) )
This is an array containing one element describing the match. The match descriptor is an array, where element 0 contains the matched sequence, and the element at index 1 contains the index of the first character of the match.
preg_match_all returns all matches, so it is similar to the g flag in JavaScript. Remember, PHP does not have the g modifier, so global matching is encoded in the public interface in the PCRE regular expression wrapper:
preg_match_all('/xy+/', 'xyxyyxyyy', $matches, PREG_OFFSET_CAPTURE);
The result contains all matches:
Array ( 
    [0] => Array ( 
        [0] => Array ( [0] => xy   [1] => 0 ) 
        [1] => Array ( [0] => xyy  [1] => 2 ) 
        [2] => Array ( [0] => xyyy [1] => 5 ) 
Although the preg_ functions act as a wrapper for Perl 5 style regular expressions, there are some small differences to the Perl syntax. Consult the documentation on PCRE pattern differences for more details.