繁体   English   中英

PHP正则表达式 - 期间问题'。' preg_match中的字符

[英]PHP Regular Expressions - Problems with period '.' character in preg_match

我正在尝试使用preg_match($regexp, $filename)来确定解析一些文件和目录的名称。 具体来说,给定一个像“directory / subdirectory / filename.h”这样的字符串,我想检查字符串是否以“filename.h”结尾

当所有文字(例如'/'和'。')被转义时,我的测试看起来像这样:

preg_match('/filename\.h$/', ''directory\/subdirectory\/filename\.h');

但是,上面的代码行返回false。

奇怪的是,以下代码行返回true。

preg_match('/\.h$/', 'directory\/subdirectory\/filename\.h');

当正则表达式为'/\\.h$/'时,有没有人知道为什么这个求值为true;而当正则表达式为'/filename\\.h$/'时,是否为false?

在您测试的字符串中,不要逃避斜杠和点。 它们在单引号字符串中被视为文字反斜杠,因此不匹配:

preg_match('/filename\.h$/', 'directory/subdirectory/filename.h');
// Matches!

需要转义第一个参数 (正则表达式)。 第二个参数是字面上的反斜杠(因为它用单引号括起来)。

考虑到这一点,您的第一个preg_match正在进行此比较:

directory\/subdirectory\/filename\.h
                         filename .h
                                 ^... This is why it doesn't match

第二个是这样做的:

directory\/subdirectory\/filename\.h
                                  .h  MATCH!

暂无
暂无

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

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