Backreference does not work in PHP

风流意气都作罢 提交于 2019-11-27 02:09:21

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'; 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!