Named capture in PHP using regex

前端 未结 2 1143
星月不相逢
星月不相逢 2020-12-13 17:32

How can I use named capture with regex in PHP? Can anyone give me a working example?

相关标签:
2条回答
  • 2020-12-13 18:13

    Doesn't work with replace , only useful for match in php

    $test="yet another test";
    
    preg_match('/(?P<word>t[^s]+)/',$test,$matches);
    
    var_dump($matches['word']);
    
    0 讨论(0)
  • 2020-12-13 18:22

    According documentation

    PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern) and (?'name'pattern)

    So you'll get same result using:

    <?php
    preg_match('/(?P<test>.+)/', $string, $matches);  // basic syntax
    preg_match('/(?<test>.+)/', $string, $matches);   // alternative
    preg_match("/(?'test'.+)/", $string, $matches);   // alternative
    

    Check result on 3v4l.org

    0 讨论(0)
提交回复
热议问题