我需要使用preg_match來獲取匹配某個條件的文件。例如,我想找到一個名爲「123-stack-overflow.txt」的文件。在.txt之後和之前可以有任何字符。preg_match獲取文件與123和.txt之間的任何字符?
這是怎麼修改的?
preg_match("/^$ID-(.+).txt/" , $name, $file);
我需要使用preg_match來獲取匹配某個條件的文件。例如,我想找到一個名爲「123-stack-overflow.txt」的文件。在.txt之後和之前可以有任何字符。preg_match獲取文件與123和.txt之間的任何字符?
這是怎麼修改的?
preg_match("/^$ID-(.+).txt/" , $name, $file);
正則表達式^123-.+\.txt$
^ # Match start of string
123- # Match the literal string 123-
(.+) # Match anything after (captured)
\.txt # Match the literal string .txt
$ # Match end of string
PHP:
$str="123-stack-overflow.txt";
preg_match('/^123-(.+)\.txt$/',$str,$match);
echo $match[0];
echo $match[1];
>>> 123-stack-overflow.txt
>>> stack-overflow
我覺得你的'*'應該是'+' – Madbreaks
你必須逃脫。 charchter
preg_match("/^$ID-(.+).txt/" , $name, $file);
應該
preg_match("/^$ID-(.+)\.txt^/U" , $name, $file);
,如果你想$ ID的每個數字istead匹配您可以使用
preg_match("/^[0-9]+-(.+)\.txt^/U" , $name, $file);
//^ beginning of line<br/>
//preg_quote($ID, '/') Properly escaped id, in case it has control characters <br/>
//\\- escaped dash<br/>
//(.+) captured file name w/out extension <br/>
//\.txt extension<br/>
//$ end of line
preg_match("/^".preg_quote($ID, '/')."\\-(.+)\\.txt$/" , $name, $file);
什麼是你的問題? –
@Madbreaks,趕緊回答它,讓我可以改變它!大聲笑 – Cofey
@Cofey有一個upvote,671是一個更好的數字:) –