我正在尝试使用preg_match($regexp, $filename)
来确定解析文件和目录的一些名称。具体来说,给定一个类似"directory/subdirectory/filename.h"的字符串,我想检查该字符串是否以"filename.h"结尾
当所有文字(例如"/"answers".")都被转义时,我的测试看起来是这样的:
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!