PHP REgEx preg_replace第一个文件夹名称(通配符)

时间:2011-04-06 14:08:21

标签: php regex wildcard

有正则表达式问题..

我有一系列目录,其中包含.htm模板...所有模板包都保存在文件夹tpl /中(不是那么重要)

tpl包含一个名为tpl_default的默认模板包。

我正在编写一个从当前模板文件中读取的函数,然后从默认目录中的同一文件中获取所有Tokens {TOKEN}。

// $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行的正则表达式“?WHAT”的问题。每次第一个目录可能不同时,我如何只匹配第一个目录和通配符?

3 个答案:

答案 0 :(得分:2)

您需要一个^锚点,以便preg_replace()仅替换第一个目录。并且您没有给出代表性文件路径的示例。 (它是以一个前导/还是可能//开头的?)在任何一种情况下,这都可以解决问题:

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

答案 1 :(得分:0)

试试这个正则表达式,我认为就是这样

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

答案 2 :(得分: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的解决方案

相关问题