preg_replace - 如何转义“[”

发布于 2024-11-27 03:27:50 字数 690 浏览 0 评论 0原文

我写了这段代码:

<?
$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花开浅夏 2024-12-04 03:27:50

您需要对括号进行双重转义:

$patterns[0] = '/\\[b/';

PHP 在解析字符串时将“消耗”单个反斜杠,只留下一个空的 [,正则表达式引擎将其视为一个字符类。通过双重转义,\\ 将被 PHP 视为转义,留下单个 \,这将被正则表达式引擎视为转义。

You need to double-escape the brackets:

$patterns[0] = '/\\[b/';

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.

巴黎盛开的樱花 2024-12-04 03:27:50

您的问题与转义 [ 无关。您的问题是您希望 $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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文