Backreference does not work in PHP

后端 未结 1 1213
南方客
南方客 2020-11-28 16:11

Lately I\'ve been studying (more in practice to tell the truth) regex, and I\'m noticing his power. This demand made by me (link), I am aware of \'backreference\'. I think I

相关标签:
1条回答
  • 2020-11-28 16:18

    It is because you use a double quoted string, inside a double quoted string \1 is read as the octal notation of a character (the control character SOH = start of heading), not as an escaped 1.

    So two ways:

    use single quoted string:

    '/\[(b|i|u|s)\]\s*(.*?)\s*\[\/\1\]/i'
    

    or escape the backslash to obtain a literal backslash (for the string, not for the pattern):

    "/\[(b|i|u|s)\]\s*(.*?)\s*\[\/\\1\]/i"
    

    As an aside, you can write your pattern like this:

    $pattern = '~\[([bius])]\s*(.*?)\s*\[/\1]~i';
    
    // with oniguruma notation
    $pattern = '~\[([bius])]\s*(.*?)\s*\[/\g{1}]~i';
    
    // oniguruma too but relative:
    // (the second group on the left from the current position)
    $pattern = '~\[([bius])]\s*(.*?)\s*\[/\g{-2}]~i'; 
    
    0 讨论(0)
提交回复
热议问题