在 PHP 正则表达式中转义反斜杠 [] 的正确方法? [英] Right way to escape backslash [ ] in PHP regex?

查看:31
本文介绍了在 PHP 正则表达式中转义反斜杠 [] 的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,我试图找出在 PHP 正则表达式模式中使用反斜杠的正确方法,如下所示:

Just out of curiosity, I'm trying to figure out which exactly is the right way to escape a backslash for use in a PHP regular expression pattern like so:

测试 01:(3 个反斜杠)

$pattern = "/^[\]{1,}$/";
$string = '\';

// ----- RETURNS A MATCH -----

测试 02:(4 个反斜杠)

$pattern = "/^[\\]{1,}$/";
$string = '\';

// ----- ALSO RETURNS A MATCH -----

根据下面的文章,4 应该是正确的方法,但让我感到困惑的是两个测试都返回了匹配项.如果两者都正确,那么 4 是首选方式吗?

According to the articles below, 4 is supposedly the right way but what confuses me is that both tests returned a match. If both are right, then is 4 the preferred way?

资源:

推荐答案

问题是,你使用的是字符类,[],所以有多少反斜杠并不重要嵌入其中,它将被视为单个反斜杠.

The thing is, you're using a character class, [], so it doesn't matter how many literal backslashes are embedded in it, it'll be treated as a single backslash.

例如以下两个正则表达式:

e.g. the following two regexes:

/[a]/
/[aa]/

就正则表达式引擎而言,所有意图和目的都是相同的.字符类采用一个字符列表并将它们折叠"下来以匹配单个字符,沿着对于正在考虑的当前字符,它是否是 [] 中列出的任何字符?".如果您在类中列出两个反斜杠,那么它将是字符是黑斜杠还是反斜杠?".

are for all intents and purposes identical as far as the regex engine is concerned. Character classes take a list of characters and "collapse" them down to match a single character, along the lines of "for the current character being considered, is it any of the characters listed inside the []?". If you list two backslashes in the class, then it'll be "is the char a blackslash or is it a backslash?".

这篇关于在 PHP 正则表达式中转义反斜杠 [] 的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆