<?php
// +----------------------------------------------------------------------
// | Created by PhpStorm.
// +----------------------------------------------------------------------
// | user : LW放下
// +----------------------------------------------------------------------
// | blog : www.putyy.com
// +----------------------------------------------------------------------
// | email: 10945014@qq.com
// +----------------------------------------------------------------------
// | Date : 2018/11/2 0002 11:30
// +----------------------------------------------------------------------
global $templateCount;
//总数
$templateCount = 0;
//绝对路径
global $absSource;
$absSource = 'http://xxx.xxx.com';
/**
* 这里只是把相对路径的css,js,jpg,png,gif,jpeg的url传递给getStyleDomain这个统一获取真实资源地址的类方法
* 执行视图文件替换
* @param $viewPath
*/
function replaceSource($cssPath){
global $absSource;
$content = file_get_contents($cssPath);
$newPath = '/skin/'.str_replace(array('../','./'),array('',''),$cssPath);
$match = '/url(["|']{0,1}([^'//|//|data:|"data:|"http|http|"https|https].*?)['|"]{0,1})/is';
$data = array();
preg_match_all($match,$content,$data);
if (!empty($data[0])) {
$old = array();
$new = array();
foreach ($data[0] as $k=>$v) {
array_push($old, $v);
$sourceUrl = $newPath;
$pathArray = explode('/', $sourceUrl);
unset($pathArray[count($pathArray) - 1]);
if (strpos($v,'../') !== false) {
$cou = substr_count($v, '../');
while ($cou){
unset($pathArray[count($pathArray) - 1]);
$cou--;
}
}
$sourceUrl = implode('/',$pathArray);
preg_match('/((['|"]*).*?(['|"]*))/',$v,$das);
$aa = $data[1][$k];
array_push($new, 'url'.$das[1].$absSource.$sourceUrl . '/' . str_replace(array('../','./'),array('',''),$aa).$das[2]);
}
$content = str_replace(array_unique($old),array_unique($new),$content);
file_put_contents($cssPath,$content);
global $templateCount;
$templateCount++;
}
return;
}
/**
* 读取文件路径
* @param $listChildren
* @param $fPath
*/
function readChildren($listChildren, $fPath)
{
foreach ($listChildren as $vv) {
if (in_array($vv, array('.', '..'))) {
continue;
}
if (is_dir($fPath . '/' . $vv)) {
readChildren(scandir($fPath . '/' . $vv), $fPath . '/' . $vv);
} elseif (is_file($fPath . '/' . $vv)) {
if(strpos($vv,'.css')!==false){
replaceSource($fPath . '/' . $vv);
}
}
}
return;
}
/**
* 初始化
* 替换所有视图文件静态资源
* 如果新增视图或者修改视图 直接配置下列数组为当前文件同级目录即可
* 该方法不保证完全成功,所以完成后最好检测一下
* 目前支持格式: jpg,png,gif,jpeg
* 资源原有格式: 1、 ~~xx/xx.png
*
* 2、 "./xxx/xxx/xxx.jpg"
*
* 3、 './xxx/xxx/xxx.jpg'
* ...............
*
* 使用方式进入该脚本目录,命令行执行 php replaceCss.php
*/
//$ignoreDir = array('./xxx/xxx/xxx/css');
//foreach ($ignoreDir as $v){
// if ( is_dir($v) ) {
// //循环读取下层文件
// readChildren(scandir( $v ), $v);
// }
//}
// 替换指定文件
$cssPath = './xxx/css/test.css';
replaceSource($cssPath);
var_dump('模板替换数量:'.$templateCount);