我试图从其他文件的内容替换一些标签的内容包括文件中使用回用file_exists引用:PHP - 中的preg_replace
$view = preg_replace('/{include ([[:alnum:]\.-]+)}/', ((file_exists('template/$1.html')) ? 'OK $1' : 'KO $1'), file_get_contents('myTemplateFile.tpl'));
所有{include file.ext}
引用我在myTemplateFile.tpl
了被替换KO file.ext
代替的OK file.ext
。
不过,如果我硬编码file_exists('template/file.ext')
,则显示正确的字符串。
在我看来后面引用不正确解决file_exists
调用中。
我在做什么错?
$contents = file_get_contents('myTemplateFile.tpl');
if ((file_exists('template/$1.html')) {
$result = preg_replace('/{include ([[:alnum:]\.-]+)}/', 'OK $1', $contents);
} else {
$result = preg_replace('/{include ([[:alnum:]\.-]+)}/', 'KO $1', $contents);
}
正如你所看到的,file_exists()
呼叫的preg_replace()
语句之前进行:
谢谢!我没有注意递归调用的解决方式......当然,在preg_replace甚至被评估之前,file_exists被首先调用! –