馃 human-readable regular expressions for PHP

Overview
 ____            _____            ____        _ _     _           ____  _   _ ____  
|  _ \ ___  __ _| ____|_  ___ __ | __ ) _   _(_) | __| | ___ _ __|  _ \| | | |  _ \ 
| |_) / _ \/ _` |  _| \ \/ / '_ \|  _ \| | | | | |/ _` |/ _ \ '__| |_) | |_| | |_) |
|  _ <  __/ (_| | |___ >  <| |_) | |_) | |_| | | | (_| |  __/ |  |  __/|  _  |  __/ 
|_| \_\___|\__, |_____/_/\_\ .__/|____/ \__,_|_|_|\__,_|\___|_|  |_|   |_| |_|_|    
           |___/           |_|                                                      

human-readable regular expressions for PHP

Travis Coveralls release

PHP port of regexpbuilderjs

RegExpBuilder integrates regular expressions into the programming language, thereby making them easy to read and maintain. Regular Expressions are created by using chained methods and variables such as arrays or strings.

Installation

composer req gherkins/regexpbuilderphp

Or download the appropriate release and require RegExpBuilder.php and RegExp.php from /src.

Documentation

https://github.com/gherkins/regexpbuilderphp/wiki

Examples

use Gherkins\RegExpBuilderPHP;
$builder = new RegExpBuilder();

Validation

exactly(2)->digits() ->then("_") ->min(3)->max(10)->letters() ->then(".") ->anyOf(array("png", "jpg", "gif")) ->endOfInput() ->getRegExp(); //true $regExp->matches("2020_10_hund.jpg"); $regExp->matches("2030_11_katze.png"); $regExp->matches("4000_99_maus.gif"); //false $regExp->matches("123_00_nein.gif"); $regExp->matches("4000_0_nein.pdf"); $regExp->matches("201505_nein.jpg");">
$regExp = $builder
    ->startOfInput()
    ->exactly(4)->digits()
    ->then("_")
    ->exactly(2)->digits()
    ->then("_")
    ->min(3)->max(10)->letters()
    ->then(".")
    ->anyOf(array("png", "jpg", "gif"))
    ->endOfInput()
    ->getRegExp();

//true
$regExp->matches("2020_10_hund.jpg");
$regExp->matches("2030_11_katze.png");
$regExp->matches("4000_99_maus.gif");

//false
$regExp->matches("123_00_nein.gif");
$regExp->matches("4000_0_nein.pdf");
$regExp->matches("201505_nein.jpg");

Search

anyOf(array(".pdf", ".doc")) ->getRegExp(); $text = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy SomeFile.pdf eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. doc_04.pdf Stet clita kasd File.doc.' $matches = $regExp->findIn($text); //true ($matches[0] === "SomeFile.pdf"); ($matches[1] === "doc_04.pdf"); ($matches[2] === "File.doc");">
$regExp = $builder
    ->multiLine()
    ->globalMatch()
    ->min(1)->max(10)->anythingBut(" ")
    ->anyOf(array(".pdf", ".doc"))
    ->getRegExp();

$text = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy SomeFile.pdf eirmod tempor invidunt ut labore et dolore
magna aliquyam erat, sed diam voluptua. At vero eos et accusam
et justo duo dolores et ea rebum. doc_04.pdf Stet clita kasd File.doc.'

$matches = $regExp->findIn($text);

//true
($matches[0] === "SomeFile.pdf");
($matches[1] === "doc_04.pdf");
($matches[2] === "File.doc");

Replace

replace( $text, function ($match) { return (int)$match + 1; } ); //true ("99 bottles of beer on the wall" === $text);">
$regExp = $builder
    ->min(1)
    ->max(10)
    ->digits()
    ->getRegExp();

$text = "98 bottles of beer on the wall";

$text = $regExp->replace(
    $text,
    function ($match) {
        return (int)$match + 1;
    }
);

//true
("99 bottles of beer on the wall" === $text);

Validation with multiple patterns

endOfInput(); $b = $builder ->getNew() ->startOfInput() ->exactly(4)->letters() ->then(".jpg") ->endOfInput(); $regExp = $builder ->getNew() ->eitherFind($a) ->orFind($b) ->getRegExp(); //true $regExp->matches("123.pdf"); $regExp->matches("456.doc"); $regExp->matches("bbbb.jpg"); $regExp->matches("aaaa.jpg"); //false $regExp->matches("1234.pdf"); $regExp->matches("123.gif"); $regExp->matches("aaaaa.jpg"); $regExp->matches("456.docx");">
$a = $builder
    ->startOfInput()
    ->exactly(3)->digits()
    ->anyOf(array(".pdf", ".doc"))
    ->endOfInput();

$b = $builder
    ->getNew()
    ->startOfInput()
    ->exactly(4)->letters()
    ->then(".jpg")
    ->endOfInput();

$regExp = $builder
    ->getNew()
    ->eitherFind($a)
    ->orFind($b)
    ->getRegExp();

//true
$regExp->matches("123.pdf");
$regExp->matches("456.doc");
$regExp->matches("bbbb.jpg");
$regExp->matches("aaaa.jpg");

//false
$regExp->matches("1234.pdf");
$regExp->matches("123.gif");
$regExp->matches("aaaaa.jpg");
$regExp->matches("456.docx");

Take a look at the tests for more examples

Comments
  • Remove deprecation warnings for flags parameter

    Remove deprecation warnings for flags parameter

    The flags parameter in preg_match and preg_match all is of type int (not string as previously asserted in the code) and not nullable. Passing null leads to a deprecation warning in newer PHP versions, which is now also checked for in the provided GitHub actions

    opened by simp42 7
  • Bump to PHP 7

    Bump to PHP 7

    Ref #22

    Changes

    • use local PHPUnit
      • easier to use with various PHP versions, autoloaded (TestCase classes)
    • use [] instead of array()
    • use implode() instead of join()
    • use strict types
    • use return types
    • drop random empty spaces
    • add composer.lock to .gitignore, since not commited
    opened by TomasVotruba 6
  • anyOf Method

    anyOf Method

    adrianmiu via reddit

    I would change ->eitherFind("png")->orFind("jpg")->orFind("gif") to something like ->anyOf(array('png', 'jpg', 'gif')) or something to that extent

    enhancement 
    opened by gherkins 5
  • Composer issue

    Composer issue

    Hi,

    when you ship this (great, by the way) project to Packagist, could you remove the .git directory. It messes up my git installation by making your code as a submodule of my code that I have many pains to push.

    Each time I update I need to manually remove your .git directory, add all your files to my change list and then I can commit.

    Thanks

    opened by Hypoaristerolactotherapist 3
  • Class 'Gherkins\RegExpBuilderPHP\RegExpBuilder' not found

    Class 'Gherkins\RegExpBuilderPHP\RegExpBuilder' not found

    I just downloaded your repo using composer require gherkins/regexpbuilderphp and started soing some tests as suggested by you. i have created new test.php file under regexpbuilderphp folder

    <?php
    namespace Gherkins\RegExpBuilderPHP;
    
    
    $builder = new \Gherkins\RegExpBuilderPHP\RegExpBuilder();
    
    $regExp = $builder
        ->startOfInput()
        ->exactly(4)->digits()
        ->then("_")
        ->exactly(2)->digits()
        ->then("_")
        ->min(3)->max(10)->letters()
        ->then(".")
        ->anyOf(array("png", "jpg", "gif"))
        ->endOfInput()
        ->getRegExp();
    
    //true
    $regExp->matches("2020_10_hund.jpg");
    $regExp->matches("2030_11_katze.png");
    $regExp->matches("4000_99_maus.gif");
    
    //false
    $regExp->matches("123_00_nein.gif");
    $regExp->matches("4000_0_nein.pdf");
    $regExp->matches("201505_nein.jpg");
    

    but i am getting error saying:

    Fatal error: Class 'Gherkins\RegExpBuilderPHP\RegExpBuilder' not found in    C:\wamp\www\gherkins\regexpbuilderphp\src\test.php on line 5
    

    can you please help.

    thanks

    opened by Fshamri 3
  • Match any 0+ of lineBreaks

    Match any 0+ of lineBreaks

    Update: found a solution, is it proper?

    I would like to match these cases:

    - <code>hello</code>
    - <code>hello
    </code>
    

    So I've created builder like this:

    $surroundingTagRegExpWithLineBreaks = (new RegExpBuilder)->startOfInput()
        ->find(sprintf('<%s', $tag))
        ->anything()
        ->min(0)->lineBreaks()
        ->find(sprintf('</%s>', $tag))
        ->endOfInput()
        ->getRegExp();
    
    

    I'd expect ->min(0)->lineBreaks() to compatible with ->any()->lineBreaks(). But it isn't.

    opened by TomasVotruba 3
  • Exact digits matching

    Exact digits matching

    I'm trying to match expression with exactly 10 digits. Maybe I don't understand it correctly, so here is my example:

    $regExp = (new RegExpBuilder)->exactly(10)->digits()->getRegExp();
    
    var_dump($regExp->test(123456789)); // should: FALSE, is FALSE
    var_dump($regExp->test(1234567890)); // should: TRUE, is TRUE
    var_dump($regExp->test(12345678901)); // should: FALSE, is TRUE
    

    How to achieve my goal?

    question 
    opened by TomasVotruba 3
  • adds workflows for testing

    adds workflows for testing

    Instead of relying on Travis we now use GitHub workflows to automatically test the application with different PHP versions. For now we test with 7.3 and 8.1

    opened by simp42 2
  • Groups & globalMatch() don't mix well

    Groups & globalMatch() don't mix well

    The group matches are ignored when adding globalMatch flag.

    $builder = new RegExpBuilder();
    $regExp = $builder->getNew()->globalMatch()
        ->then('Foo of ')
        ->append($builder->getNew()->anythingBut(' '))
        ->asGroup()
        ->getRegExp();
    
    $string = 'Foo of Bar Foo of Dummy';
    $output = $regExp->findIn($string);
    

    outputs this, where can see that group matches is missing:

    array (2)
     路 [0]: string (10) "Foo of Bar"
     路 [1]: string (12) "Foo of Dummy"
    

    So I added one more condition to RegExp.php:114 :

    if (!isset($matches[1]) && isset($matches[0]) && is_array($matches[0])) {
        return $matches[0];
    }
    

    tests pass and it outputs this now:

     路 [0]: array (2)
     路  路 [0]: string (10) "Foo of Bar"
     路  路 [1]: string (12) "Foo of Dummy"
     路 [1]: array (2)
     路  路 [0]: string (3) "Bar"
     路  路 [1]: string (5) "Dummy"
    

    Should I make a PR?

    opened by younes0 2
  • added capture name

    added capture name

    note that, if named, the group will be included twice in the preg_match array:

       [0]: string (49) "n掳 1802"
     路 [myname]: string (4) "1802"
     路 [1]: string (4) "1802"
    
    opened by younes0 2
  • group name

    group name

    feature to implement, see: http://stackoverflow.com/questions/6971287/named-capture-in-php-using-regex

    I may do a PR, if you have any recommendations, please share

    opened by younes0 2
Releases(1.1.0)
Owner
Max Girkens
Let's Push Things Forward
Max Girkens
Fluent regular expressions in PHP

FLUX (Fluent Regex) 0.5.2 by Selvin Ortiz Description Fluent Regular Expressions in PHP inspired by and largely based on VerbalExpressions:JS by Jesse

Selvin Ortiz 341 Nov 20, 2022
This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized objects in DynamoDB 馃殌.

DynamoDB Storable This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized

Matthieu W. 2 Jun 19, 2022
Best regular expression for gmail

best regular expression for gmail Gmail Regular expression with all details (not start with dot,number , is it possible to use multiple dot but not in

null 3 Feb 2, 2022
High performance view templating API for PHP applications using tags & expressions inspired by Java JSTL and C compiler

View Language API Table of contents: About Expressions Tags Configuration Compilation Installation Unit Tests Examples Reference Guide About This API

Lucian Gabriel Popescu 0 Jan 9, 2022
Enable method chaining or fluent expressions for any value and method.

PHP Pipe Operator A (hopefully) temporary solution to implement the pipe operator in PHP. Table of contents Requirements How to install How to use The

Sebastiaan Luca 268 Dec 26, 2022
Clean Code concepts adapted for PHP - A guide for producing readable, reusable, and refactorable PHP software

Clean Code concepts adapted for PHP - A guide for producing readable, reusable, and refactorable PHP software

Fabio Soares 172 Dec 25, 2022
A PHP package for MRZ (Machine Readable Zones) code parser for Passport, Visa & Travel Document (TD1 & TD2).

MRZ (Machine Readable Zones) Parser for PHP A PHP package for MRZ (Machine Readable Zones) code parser for Passport, Visa & Travel Document (TD1 & TD2

Md. Rakibul Islam 25 Aug 24, 2022
The easiest way to match data structures like JSON/PlainText/XML against readable patterns. Sandbox:

PHP Matcher Library created for testing all kinds of JSON/XML/TXT/Scalar values against patterns. API: PHPMatcher::match($value = '{"foo": "bar"}', $p

Coduo 774 Dec 31, 2022
Humanize values that are readable only for developers.

PHP Humanizer Tests - 4.x Readme for 4.x version Humanize values to make them readable for regular people ;) Installation Run the following command: c

Coduo 1.5k Dec 21, 2022
A wrapper around symplify/config-transformer used to update recipes and using easy coding standard for generating readable config files.

Symfony Recipes Yaml to PHP Converter This is a wrapper around the symplify/config-transformer used to convert Symfony core recipes which uses .yaml c

Alexander Schranz 3 Nov 24, 2022
OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures all the essential functionalities required for any enterprise.

OrangeHRM Open Source Application OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures all the essential functionalities

OrangeHRM 452 Jan 4, 2023
The new, most powerful Comic Reader ever created by the human race. Reworked by an Otaku.

FoOlSlideX The new, most powerful Comic Reader ever created by the human race. Reworked by an Otaku. Requirements PHP greater than 7.0 and everything

saintly2k 21 Dec 21, 2022
Text - An experiment with WebSockets and the human condition.

An experiment with WebSockets and the human condition. I wanted to learn how to use WebSockets in pure PHP and JavaScript, so I came up with the simpl

Greg Bowler 52 Dec 12, 2022
Sentrifugo is a FREE and powerful Human Resource Management System (HRMS) that can be easily configured to meet your organizational needs.

Sentrifugo Sentrifugo is a free and powerful new-age Human Resource Management System that can be easily configured to adapt to your organizational pr

Sentrifugo 447 Dec 27, 2022
The Current US Version of PHP-Nuke Evolution Xtreme v3.0.1b-beta often known as Nuke-Evolution Xtreme. This is a hardened version of PHP-Nuke and is secure and safe. We are currently porting Xtreme over to PHP 8.0.3

2021 Nightly Builds Repository PHP-Nuke Evolution Xtreme Developers TheGhost - Ernest Allen Buffington (Lead Developer) SeaBeast08 - Sebastian Scott B

Ernest Buffington 7 Aug 28, 2022
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 272 Dec 22, 2022
PHP Meminfo is a PHP extension that gives you insights on the PHP memory content

MEMINFO PHP Meminfo is a PHP extension that gives you insights on the PHP memory content. Its main goal is to help you understand memory leaks: by loo

Benoit Jacquemont 994 Dec 29, 2022
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 258 Sep 15, 2022
A multithreaded application server for PHP, written in PHP.

appserver.io, a PHP application server This is the main repository for the appserver.io project. What is appserver.io appserver.io is a multithreaded

appserver.io 951 Dec 25, 2022