2011-04-06 36 views
2

有正則表達式的問題..PHP正則表達式的preg_replace第一個文件夾的名稱(通配符)

我有一系列持有的.htm模板目錄...所有模板包在文件夾TPL舉行/(不是真的那麼重要)

tpl包含名爲tpl_default的默認模板包。

我正在寫一個函數,它從當前模板文件讀取,然後從默認目錄中的相同文件獲取所有令牌{令牌}。

// $file returns abundant/index/index.htm as an example. So need to change that to read tpl_default/index/index.htm 
$file = preg_replace('/?WHAT/','tpl_default',$file); // loose the first directory and replace with the default dir.... 
$default_file = file_get_contents("../../tpl/".$file); 
// read the default template and pull all the tokens.... 
$subject = $default_file; 
$pattern = "/{.*?}/";          
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); 
return $matches; // TODO: convert matches to <li> element 

在第1行真正出現了「正確的」正則表達式問題。每次第一個目錄可能會有所不同,那麼我如何才能將第一個目錄與通配符匹配?

回答

2

你需要一個^錨,這樣preg_replace()僅替換的第一個目錄。你沒有給出一個有代表性的文件路徑的例子。 (?它與一家領先的/或可能//開始)在任何情況下,本應該做的伎倆:

$file = preg_replace('%^(/*)[^/]+%','$1tpl_default',$file); 
+0

優秀!是的,你是非常正確的,它只需要找到第一個目錄,僅供參考,我在代碼中包含了文件路徑的示例.. // $ file返回的是豐富的/ index/index.htm作爲示例。所以需要改變,以讀取tpl_default/index/index.htm 這一個像魅力雖然 - 很多謝謝。 – Nick 2011-04-06 15:54:11

0

試試這個正則表達式,我認爲這是它

'\/[\w\s_-]+\/' 
+0

我編輯過,請嘗試一下。 – Headshota 2011-04-06 14:23:23

0

的解決方案是:

$pattern1 = "%^(/*)[^/]+%"; 
$default_file = preg_replace($pattern1,'tpl_default',$file); // loose the first 
$default_file = file_get_contents("../../tpl/".$default_file); 
$subject = $default_file; 
$pattern = '/\{.*?\}/';           
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); 
return $matches; 

由於去ridgerunner爲解決