2012-12-07 37 views
3

我需要使用preg_match來獲取匹配某個條件的文件。例如,我想找到一個名爲「123-stack-overflow.txt」的文件。在.txt之後和之前可以有任何字符。preg_match獲取文件與123和.txt之間的任何字符?

這是怎麼修改的?

preg_match("/^$ID-(.+).txt/" , $name, $file); 
+0

什麼是你的問題? –

+0

@Madbreaks,趕緊回答它,讓我可以改變它!大聲笑 – Cofey

+0

@Cofey有一個upvote,671是一個更好的數字:) –

回答

2

正則表達式^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 
+0

我覺得你的'*'應該是'+' – Madbreaks

0

你必須逃脫。 charchter

preg_match("/^$ID-(.+).txt/" , $name, $file); 

應該

preg_match("/^$ID-(.+)\.txt^/U" , $name, $file); 

,如果你想$ ID的每個數字istead匹配您可以使用

preg_match("/^[0-9]+-(.+)\.txt^/U" , $name, $file); 
2
//^ 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); 
相關問題