taeluf/better-regex

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

This package is auto-updated.

Last update: 2024-09-29 02:18:47 UTC


README

Better Regex

多行正则表达式,带有注释和函数。

特性

  • 注释
  • ::functions(arg1 ;; {{array_item_1}}{{array_item_2}} ;; arg3)
    • $br->handle('functions', function(string $arg1, array $arg2, string $arg3){return 'a string';})
  • 多行(abc<NEWLINE>def 生成 abcdef

附加功能

  • 去除行首空格
  • 行尾转义空格 pattern \ NEWLINE
  • 转义井号 pattern \# pattern(文本井号)
  • 转义反斜杠 pattern \\NEWLINE (保留 \\

安装

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

或者在你的 composer.json

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

完整示例

<?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  
);  

版本

  • v0.3 是一个过时且设计糟糕的版本
  • v0.4 可以使用
  • 未来计划:我不期望对这个库做太多修改。它已经很好用,也不需要更多功能。它可能在某个时候添加一些内置的 ::functions() 或更好的语法?但这不重要。

故障排除/额外内容

  • 我认为注释需要在 # 前面有一个空格
  • 注释和多行在 php 中通常通过 PCRE_EXTENDED 标志可用