正则表达式中特殊字符的含义
我已经挖掘 codeigniter 几个小时了。我在路由器类中发现了一些不同的正则表达式。
preg_match('#^'.$key.'$#', $uri);
preg_replace('#^'.$key.'$#', $val, $uri);
我制作了一个测试 php 文件,如下所示:
<?php
$route['login'] = 'user/login';
$route['user/([a-zA-Z-]+)'] = 'user/profile/$1';
$uri = 'user/asfd';
foreach ($route as $key => $val)
{
if (preg_match('#^'.$key.'$#', $uri))
{
echo preg_replace('#^'.$key.'$#', $val, $uri);
}
}
它正确给出了
user/profile/asfd
我在这里没有得到的是 #^ 和 $# 的用法。我在网上爬行寻找一些解释,但没有运气。
I have been digging codeigniter for some hours. I found some different regex in router class.
preg_match('#^'.$key.'$#', $uri);
preg_replace('#^'.$key.'$#', $val, $uri);
i made a test php file as below:
<?php
$route['login'] = 'user/login';
$route['user/([a-zA-Z-]+)'] = 'user/profile/$1';
$uri = 'user/asfd';
foreach ($route as $key => $val)
{
if (preg_match('#^'.$key.'$#', $uri))
{
echo preg_replace('#^'.$key.'$#', $val, $uri);
}
}
it correctly gives
user/profile/asfd
What i don't get here is the usage of #^ and $#. I've crawled the web to find some explanation but no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在本例中,开头和结尾的
#
是正则表达式的分隔符。您以前可能已经将它们视为/
,但可以使用许多不同的字符。它们仅表示正则表达式模式的开始和结束,后面可能跟着其他正则表达式选项,例如不区分大小写 (i
)、全局匹配 (g
) 等(尽管在 PHP 中使用preg_match_all()
代替g
标志)因此,实际匹配的模式是
^$key$
。即要匹配的字符串的开头、$key
的值以及字符串的结尾。选择
#
而不是/
作为此表达式中的分隔符的可能原因是,它消除了使用\
转义 URI 模式斜杠的需要。In this instance, the beginning and ending
#
are the regular expression's delimiters. You've probably seen them before as/
, but many different characters can be used. They merely signify the beginning and end of the regex pattern, and may be followed by additional regex options, like case-insensitivity (i
), global matching (g
), etc (thoughpreg_match_all()
is used instead of theg
flag in PHP)So, the actual pattern being matched is
^$key$
. That is, the beginning of the string to match, the value of$key
, and the end of the string.The likely reason for selecting
#
instead of/
as delimiters in this expression is that it eliminates the need to escape the URI pattern's slashes with\
.它们是正则表达式分隔符,如 PHP 手册中所述。 preg_* 函数来自 PCRE(Perl 兼容正则表达式)库。 Perl 支持文字正则表达式,使用正则表达式分隔符,就像字符串使用单引号和双引号一样。 PHP 不支持文字正则表达式,但该库仍然需要分隔符。
They're regex delimiters, as explained in the PHP manual. The preg_* functions come from the PCRE (Perl Compatible Regular Expression) library. Perl supports literal regexes, using regex delimiters rather like how strings use single and double quotes. PHP doesn't support literal regexes, but the library still requires the delimiters.