RegExpBuilderPHP – PHP Regular Expression Builder

There this really useful tool for JS, called RegExpBuilder.
It enables you to build regular expressions with a nice human-readable & chainable syntax.
(read more about it here and here)

As it’s not that much lines of code, I decided to do a port for PHP – et voila:

This is basically regex with PHP the easy way:

Say you want to validate some currency string like “€ 105,99” but want “€ 12.000,95” to be also valid.
Coming up with a regex for that i would find challenging, to say the least.

PHP RegExpBuilder to the rescue:

(you can simply install it via composer)

composer require gherkins/regexpbuilderphp:dev-master

Then you’ll be able to do:

$builder = new \Gherkins\RegExpBuilderPHP\RegExpBuilder();
$builder1 = $builder
//builder 1 will take care of the cases without a thousand-seperator
$builder1->getRegExp()->test("€ 128,99");     //true
$builder1->getRegExp()->test("€ 81,99");      //true
$builder2 = $builder->getNew()
//builder 1 will take care of the cases *with* the thousand-seperator
$builder2->getRegExp()->test("€ 1.228,99");   //true
$builder2->getRegExp()->test("€ 452.000,99"); //true
//you can then combine both builders to get a regex which handles all cases:
$combined = $this->r->getNew()
$combined->getRegExp()->test("€ 128,99");     //true
$combined->getRegExp()->test("€ 81,99");      //true
$combined->getRegExp()->test("€ 1.228,99");   //true
$combined->getRegExp()->test("€ 452.000,99"); //true

This might be a bit verbose if you don’t have any problem with:


..but I really do like it ;)

4 Replies to “RegExpBuilderPHP – PHP Regular Expression Builder”

Leave a Reply

Your email address will not be published. Required fields are marked *