Regex $1, $2, etc

后端 未结 2 1416
轻奢々
轻奢々 2021-02-04 01:40

I\'ve been trying to do some regex operations in PHP, and I\'m not very skilled in this area. It seems that when I use a regex function like preg_replace on a string, I can acce

相关标签:
2条回答
  • 2021-02-04 01:50

    They are called backreferences and match grouped elements within the regexp.

    If you surround a section of the regexp with brackets, then you can refer to it in the replace section (or indeed later in the same regexp, by the backreference which corresponds to its position.

    Slash form, or dollar form can be used in replacements:

    \1, \2 == $1, $2
    
    0 讨论(0)
  • 2021-02-04 02:10

    These are known in regex terminology as backreferences (more on that here). You use them to refer to capture groups (or subpatterns, surrounded by ()) within your regex or in the replacement string.

    An example:

    /* 
     * Replaces abcd123 with 123abcd, or asdf789 with 789asdf.
     * 
     * The $1 here refers to the capture group ([a-z]+),
     * and the $2 refers to the capture group ([0-9]+).
     */
    preg_replace('/([a-z]+)([0-9]+)/', '$2$1', $str);
    
    0 讨论(0)
提交回复
热议问题