2011-04-06 97 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为解决