taeluf/better-regex

v0.4.x-dev 2022-03-28 20:55 UTC

This package is auto-updated.

Last update: 2024-04-29 01:29:17 UTC


README

Multi-line regex with comments and functions.

Features

  • # comments
  • ::functions(arg1 ;; {{array_item_1}}{{array_item_2}} ;; arg3)
    • $br->handle('functions', function(string $arg1, array $arg2, string $arg3){return 'a string';})
  • multi-line (abc<NEWLINE>def yields abcdef)

Additional Functionality

  • trimmed lines
  • End of line escaped space pattern \ NEWLINE
  • escaped hash pattern \# pattern (literal hashtag)
  • escaped backslash pattern \\NEWLINE (preserves the \\)

Install

composer require taeluf/better-regex v0.4.x-dev   

or in your composer.json

{"require":{ "taeluf/better-regex": "v0.4.x-dev"}}  

Full Example

<?php  
$reg = <<<REGEX  
    /abc\ # abc then a space  
        ( # join referenced regexes with a |  
        ::combine({{one}}{{two}}{{three}} ;; | )  
        )\\ # literal backslash  
  
        \# # literal hashtag (then comment)  
    xyz/  
REGEX;  
$reg_refs = [  
    'one'=>'(1|one|uno)',  
    'two'=>'(2|two|dos)',  
    'three'=>'(3|three|tres)',  
    'four'=>'(4|four|quatro)'  
];  
$br = new \Breg();  
$br->handle('combine',  
    function(array $keys, string $joiner) use ($reg_refs){  
        // make an array of only the selected regs  
        $regs = [];  
        foreach ($keys as $k){  
            $regs[] = $reg_refs[$k];  
        }  
        return implode($joiner, $regs);  
    }  
);  
$final = $br->parse($reg);  
  
$this->compare(  
    '/abc\ ((1|one|uno)|(2|two|dos)|(3|three|tres))\\\\#xyz/',  
    $final,  
);  
$this->is_true(  
    preg_match($final, 'abc dos\\#xyz/') === 1  
);  

Versions

  • v0.3 is an old, terribly designed version
  • v0.4 is good to go
  • Future plans: I don't expect to change this library much. It works and it doesn't need more features. It MIGHT get some built-in ::functions() or a nicer syntax at some point? But it doesn't matter.

Troubleshooting / Extra Stuff

  • I think comments require a space before the #
  • comments & multi-line are available with the PCRE_EXTENDED flag in php normally