向后引用在PHP中不起作用 [英] Backreference does not work in PHP
问题描述
最近我一直在研究正则表达式(更多的是说实话),我注意到了他的力量.我知道我的这种要求(链接) 反向引用".我想我了解它是如何工作的,它可以在JavaScript中工作,而在PHP中则不是.
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 understand how it works, it works in JavaScript, while in PHP not.
例如,我有以下字符串:
For example I have this string:
[b]Text B[/b]
[i]Text I[/i]
[u]Text U[/u]
[s]Text S[/s]
并使用以下正则表达式:
And use the following regex:
\[(b|i|u|s)\]\s*(.*?)\s*\[\/\1\]
此在 regex101.com 上进行测试的方法,对于JavaScript相同,但无效使用PHP.
This testing it on regex101.com works, the same for JavaScript, but does not work with PHP.
preg_replace
的示例(不起作用):
Example of preg_replace
(not working):
echo preg_replace(
"/\[(b|i|u|s)\]\s*(.*?)\s*\[\/\1\]/i",
"<$1>$2</$1>",
"[b]Text[/b]"
);
虽然这种方式有效:
echo preg_replace(
"/\[(b|i|u|s)\]\s*(.*?)\s*\[\/(b|i|u|s)\]/i",
"<$1>$2</$1>",
"[b]Text[/b]"
);
感谢每个帮助我的人,我不明白自己在哪里错了.
I can not understand where I'm wrong, thanks to everyone who helps me.
推荐答案
这是因为您使用了双引号字符串,所以在双引号字符串\1
内将其读取为字符的八进制表示法(控制字符SOH =开头),而不是转义的1.
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.
有两种方法:
使用单引号字符串:
'/\[(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';
这篇关于向后引用在PHP中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!