简体   繁体   中英

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. Specifically, given a string like "directory/subdirectory/filename.h," I want to check whether the string ends in "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.

Oddly, the following line of code returns 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$/' ?

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:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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