简体   繁体   English

正则表达式中特殊字符的含义

[英]The meaning of special characters in Regex

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文件,如下所示:

<?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. 我已经在网上搜寻了一些解释,但是没有运气。

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 (though preg_match_all() is used instead of the g flag in PHP) 它们仅表示正则表达式模式的开始和结束,并且可能后跟其他正则表达式选项,例如不区分大小写( i ),全局匹配( g )等(尽管在PHP中使用了preg_match_all()代替了g标志) )

So, the actual pattern being matched is ^$key$ . 因此,匹配的实际模式是^$key$ That is, the beginning of the string to match, the value of $key , and the end of the string. 也就是说,要匹配的字符串的开头, $key的值和字符串的结尾。

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 \\ . 在此表达式中选择#而不是/作为分隔符的可能原因是,它消除了用\\转义URI模式斜杠的需要。

They're regex delimiters , as explained in the PHP manual. 它们是regex分隔符 ,如PHP手册中所述。 The preg_* functions come from the PCRE (Perl Compatible Regular Expression) library. preg_ *函数来自PCRE(与Perl兼容的正则表达式)库。 Perl supports literal regexes, using regex delimiters rather like how strings use single and double quotes. Perl使用正则表达式定界符来支持文字正则表达式,就像字符串如何使用单引号和双引号一样。 PHP doesn't support literal regexes, but the library still requires the delimiters. PHP不支持文字正则表达式,但是库仍然需要定界符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM