方法一:修改:Smarty_Compiler.class.php 即在compile为php文件时用正则表达式替换
在_compile_file 方法中用正则表达式替换$compiled_content(即模板文件内容字符串)
/* 修正css路径 */
$compiled_content = preg_replace('/(<link/shref=["|/'])(?:/.//|/././/)?(css//)?([a-z0-9A-Z_]+/.css
["|/']/srel=["|/']stylesheet["|/']/stype=["|/']text//css["|/'])/i','/1' . $this->template_dir . '/2/3',
$compiled_content);
/* 修正js目录下js的路径 */
$compiled_content = preg_replace('/(<script/s(?:type|language)=["|/']text//javascript["|/']/ssrc=
["|/'])(?:/.//|/././/)?(js//[a-z0-9A-Z_/-/.]+/.(?:js|vbs)["|/']><//script>)/', '/1' . $this->template_dir .
'/2', $compiled_content);
$pattern = array(
'/<!--[^>|/n]*?({.+?})[^<|{|/n]*?-->/', // 替换smarty注释
'/<!--[^<|>|{|/n]*?-->/', // 替换不换行的html注释
'/(href=["|/'])/././/(.*?)(["|/'])/i', // 替换相对链接
'/((?:background|src)/s*=/s*["|/'])(?:/.//|/././/)?(images//.*?["|/'])/is', // 在images前加上
$tmp_dir
'/((?:background|background-image):/s*?url/()(?:/.//|/././/)?(images//)/is', // 在images前加上
$tmp_dir
'/([/'|"])/././//is', // 以../开头的路径全部修正为空
);
$replace = array(
'/1',
'',
'/1/2/3',
'/1' . $this->template_dir . '/2',
'/1' . $this->template_dir . '/2',
'/1'
);
$compiled_content = preg_replace($pattern, $replace, $compiled_content);
方法二:
修改Smart.class.php
在_compile_source方法中
调用_compile_file后
调用自定义的替换类方法或函数
注意调用时要返回$compiled_content 即functionName(&$comiled_content,…,…){ ……;}
或在定义方法或数时在参数前加上&字符
$compiled_content为compile后的模板文件内容字符串
function _compile_source{
……
replaceUserDir($compiled_content);
……
}
/**
* 替换图片 javaScript CSS文件 路径
* @param $compiled_content temple file content
*/
function replaceUserDir(&$compiled_content,$tpl_dir='tpl/default/'){
/**
*
* 替换图片 javaScript CSS文件 路径
*/
/* 修正css路径 */
$compiled_content = preg_replace('/(<link/shref=["|/'])(?:/.//|/././/)?(css//)?([a-z0-9A-Z_]+/.css
["|/']/srel=["|/']stylesheet["|/']/stype=["|/']text//css["|/'])/i','/1' . $tpl_dir . '/2/3',
$compiled_content);
/* 修正js目录下js的路径 */
$compiled_content = preg_replace('/(<script/s(?:type|language)=["|/']text//javascript["|/']/ssrc=
["|/'])(?:/.//|/././/)?(js//[a-z0-9A-Z_/-/.]+/.(?:js|vbs)["|/']><//script>)/', '/1' . $tpl_dir . '/2',
$compiled_content);
$pattern = array(
'/<!--[^>|/n]*?({.+?})[^<|{|/n]*?-->/', // 替换smarty注释
'/<!--[^<|>|{|/n]*?-->/', // 替换不换行的html注释
'/(href=["|/'])/././/(.*?)(["|/'])/i', // 替换相对链接
'/((?:background|src)/s*=/s*["|/'])(?:/.//|/././/)?(images//.*?["|/'])/is', // 在images前加上
$tmp_dir
'/((?:background|background-image):/s*?url/()(?:/.//|/././/)?(images//)/is', // 在images前加上
$tmp_dir
'/([/'|"])/././//is', // 以../开头的路径全部修正为空
);
$replace = array(
'/1',
'',
'/1/2/3',
'/1' . $tpl_dir . '/2',
'/1' . $tpl_dir . '/2',
'/1'
);
$compiled_content = preg_replace($pattern, $replace, $compiled_content);
}