简体   繁体   English

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

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

I'm trying to use preg_match($regexp, $filename) to determine parse some names of files and directories. 我正在尝试使用preg_match($regexp, $filename)来确定解析一些文件和目录的名称。 Specifically, given a string like "directory/subdirectory/filename.h," I want to check whether the string ends in "filename.h" 具体来说,给定一个像“directory / subdirectory / filename.h”这样的字符串,我想检查字符串是否以“filename.h”结尾

When all literals (eg '/' and '.') are escaped, my test looks like this: 当所有文字(例如'/'和'。')被转义时,我的测试看起来像这样:

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

However, the above line of code returns false. 但是,上面的代码行返回false。

Oddly, the following line of code returns true. 奇怪的是,以下代码行返回true。

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

Does anyone know why this evaluates to true when the regular expression is '/\\.h$/' but false when the regexp is '/filename\\.h$/' ? 当正则表达式为'/\\.h$/'时,有没有人知道为什么这个求值为true;而当正则表达式为'/filename\\.h$/'时,是否为false?

In the string you test, don't escape the slashes and dots. 在您测试的字符串中,不要逃避斜杠和点。 They are treated as literal backslashes inside the single quoted string, and therefore don't match: 它们在单引号字符串中被视为文字反斜杠,因此不匹配:

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

You only need to escape the first argument (the regular expression). 需要转义第一个参数 (正则表达式)。 The second argument is taking the backslash literally (because it is enclosed in single quotes). 第二个参数是字面上的反斜杠(因为它用单引号括起来)。

With this in mind, your first preg_match is doing this comparison: 考虑到这一点,您的第一个preg_match正在进行此比较:

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

And the second one is doing this: 第二个是这样做的:

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

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

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