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:
https://github.com/gherkins/regexpbuilderphp
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 ->find("€") ->exactly(1)->whitespace() ->min(1)->digits() ->then(",") ->digit() ->digit(); //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() ->find("€") ->exactly(1)->whitespace() ->min(1)->digits() ->then(".") ->exactly(3)->digits() ->then(",") ->digit() ->digit(); //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() ->either($builder1) ->orLike($builder2); $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:
(?:(?:(?:(?:€){1,1})(?:(?:\s){1,1})(?:(?:(?:\d)){1,})(?:(?:,){1,1})(?:\d)(?:\d))|(?:(?:(?:€){1,1})(?:(?:\s){1,1})(?:(?:(?:\d)){1,})(?:(?:\.){1,1})(?:(?:(?:\d)){3,3})(?:(?:,){1,1})(?:\d)(?:\d)))
..but I really do like it ;)
RT @nerdpress_org: regexpbuilderphp – #PHP Regular Expression Builder http://t.co/K2BkibgNNm #regex #tool
RT @nerdpress_org: regexpbuilderphp – #PHP Regular Expression Builder http://t.co/K2BkibgNNm #regex #tool
regexpbuilderphp – #PHP Regular Expression Builder http://t.co/BaCHSJIuKb #regex #tool
RT @RegexDaily: regexpbuilderphp – #PHP Regular Expression Builder http://t.co/BaCHSJIuKb #regex #tool