[英]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.