preg_replace - 如何转义“[”
我写了这段代码:
<?
$text='how are you [b] today [/b]';
$patterns = array();
$patterns[0] = '/\[b/';
$patterns[1] = '/\b]/';
$replacements = array();
$replacements[1] = 'b]aaa<>';
$replacements[0] = '<>aaa[b';
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $text);
echo "_";
echo $text;
echo "_";
echo "END";
?>
输出显示:
how are you <>aaa[bb]aaa<> today [/b]aaa<>______how are you [b] today [/b]______END
但输出应该是:
how are you <>aaa[b] today [/b]aaa<>______how are you [b] today [/b]______END
我做错了什么?请帮忙。谢谢
I wrote this code:
<?
$text='how are you [b] today [/b]';
$patterns = array();
$patterns[0] = '/\[b/';
$patterns[1] = '/\b]/';
$replacements = array();
$replacements[1] = 'b]aaa<>';
$replacements[0] = '<>aaa[b';
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $text);
echo "_";
echo $text;
echo "_";
echo "END";
?>
the output shows:
how are you <>aaa[bb]aaa<> today [/b]aaa<>______how are you [b] today [/b]______END
but the output should be:
how are you <>aaa[b] today [/b]aaa<>______how are you [b] today [/b]______END
what did I do wrong? Please help. Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要对括号进行双重转义:
PHP 在解析字符串时将“消耗”单个反斜杠,只留下一个空的
[
,正则表达式引擎将其视为一个字符类。通过双重转义,\\
将被 PHP 视为转义,留下单个\
,这将被正则表达式引擎视为转义。You need to double-escape the brackets:
A single backslash will be "consumed" by PHP when it parses the string, leaving just a bare
[
, which will be seen by the regex engine as the beginning of a character class. By double-escaping, the\\
will be seen by PHP as an escape, leaving a single\
, which will be seen by the regex engine as an escape.您的问题与转义
[
无关。您的问题是您希望 $patterns[1] 仅匹配“/b]”,但这不是您在正则表达式中编写的内容。请尝试使用
'/\/b]/'
,或使用备用分隔符(例如'!/b]!'
)以避免牙签倾斜综合症。Your problem has nothing to do with escaping
[
. Your problem is that you want$patterns[1]
to only match "/b]" but that's not what you wrote in your regular expression.Try
'/\/b]/'
instead, or use alternate delimiters (e.g.'!/b]!'
) to avoid leaning-toothpick syndrome.