搜尋
首頁後端開發php教程如何使用php脚本给html中引用的js和css路径打上版本号_php实例

在搜索引擎中搜索关键字.htaccess 缓存,你可以搜索到很多关于设置网站文件缓存的教程,通过设置可以将css、js等不太经常更新的文件缓存在浏览器端,这样访客每次访问你的网站的时候,浏览器就可以从浏览器的缓存中获取css、js等,而不必从你的服务器读取,这样在一定程度上加快了网站的打开速度,又可以节约一下你的服务器流量。

具体文字说明不给大家多说了,下面通过代码实例给大家讲解。

比如

<link rel="stylesheet" type="text/css" href="./css/globel.css">
<script src="./js/config.js"></script>

中的href和src加上版本

<link rel="stylesheet" type="text/css" href="./css/globel.css&#63;eslc-app=3-0-2">
<script src="./js/config.js&#63;eslc-app=3-0-2"></script>

当然如果不是前后端 分离得干干净净的,就没必要这么额外的这样自己在写个脚本去打版本。

打版本的好处:

解决外部引用文件实时更新问题。比如

pc端上主要体现在 iframe中的外部引用文件不会实时更新。

wap端上部分app也是比如微信。 如果你的网页是嵌到自己的app,那也更不用说了。

用php写了个类

//生成版本
//清除版本
class ReplaceVersion{
 protected $filePostFixs = array();
 protected $versionName = null;
 protected $version = null;
 protected $path = null;
 /**
  * @param mixed $configs 
  * @param [type] $profix [description]
  * @param [type] $path  [description]
  */
 public function __construct($configs, $profix, $path){
  if (!$this->isCanRun()) {
   $this->error('必须在内网环境 10.10.0开头才可运行'); //exit;
  }
  $this->setVersion($configs);
  $this->setFilePostFix($profix);
  $this->path = $path;
 }
 protected function isCanRun(){
  if (strpos($_SERVER['HTTP_HOST'], '10.10.0') !== false) {
   return true;
  }
  return false;
 }
 /**
  * 匹配到script节点
  * @param array $match 匹配到的script
  * @return string 处理好的script
  */
 protected function callbackScript($match){
  //["<script src="../js/config.js&#63;is=new"></script>", "../js/config.js", "&#63;is=new"]
  /*/<script.*&#63;src=\"(.*&#63;)(\&#63;.*&#63;|\&#63;)&#63;\".*&#63;><\/script>/*/
  $str = $match[0];
  $pattern = '/(<script.*&#63;src=\")(.*)&#63;(\"><\/script>)/';
  return $this->callbackMatch($str, $pattern);
 }
 /**
  * 匹配到css节点
  * @param array $match 匹配到的css
  * @return string 处理好的css
  */
 protected function callbackCss($match){
  // '<link rel="stylesheet" type="text/css" href="../css/globel.css">';
  $str = $match[0];
  $pattern = '/(<link.*&#63;href=\")(.*)&#63;(\".*&#63;>)/';
  return $this->callbackMatch($str, $pattern);
 }
 /**
  * 回调模式匹配
  * @param string $str 
  * @param string $pattern
  * @return string  
  */
 protected function callbackMatch($str, $pattern){
  switch ($this->dealFlag) {
   case 'replace':
    return $this->replaceCallbackMatch($str, $pattern);
   case 'clean':
    return $this->cleanCallbackMatch($str, $pattern);
   default:
    $this->error('非法模式');
  }
 }
 /**
  * 替换版本
  * @param string $str 待处理的string
  * @param string $pattern 正则
  * @return string  处理后的string
  */
 protected function replaceCallbackMatch($str, $pattern){
  if (!preg_match($pattern, $str, $third)) {
   return $str;
  }
  $arr  = explode('&#63;', $third[2]);
  $len  = count($arr);
  $versionName = $this->versionName;
  $version = $this->version;
  if ($len === 1) {//没有问号
   $arr[0] .= '&#63;'. $versionName. '='. $version;
  }else{//有问号
   if (preg_match('/(^|\&)'. $versionName.'=(.*&#63;)($|\&)/', $arr[1])) {//存在
    $arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*&#63;)($|\&)/', '$1'. $versionName.'='. $version. '$3', $arr[1]);
    $arr[0] .= '&#63;'. $arr[1];
   }else{//不存在
    $arr[0] .= '&#63;'. $arr[1]. '&'. $versionName. '='. $version;
   }
  }
  return $third[1]. $arr[0]. $third[3];
 }
 /**
  * 清除版本
  * @param string $str 待清除的版本
  * @param string $pattern 正则
  * @return string  清除后的string
  */
 protected function cleanCallbackMatch($str, $pattern){
  if (!preg_match($pattern, $str, $third)) {
   return $str;
  }
  $arr  = explode('&#63;', $third[2]);
  $len  = count($arr);
  $versionName = $this->versionName;
  if ($len > 1 && strpos($arr[1], $versionName. '=') !== false) {
   $arr[1] = preg_replace('/(^|\&)'. $versionName.'=(.*&#63;)($|\&)/', '$1', $arr[1]);
   substr($arr[1], -1) === '&' && ($arr[1] = substr($arr[1], 0, -1));
   $arr[0] .= strlen($arr[1]) > 0 &#63; '&#63;'. $arr[1] : '';
   $str = $third[1]. $arr[0]. $third[3];
  }
  return $str;
 }
 /**
  * 执行
  */
 protected function run(){
  if ($this->path == '') {
   $this->error('empty path');
   return ;
  }
  if (is_dir($this->path)) {
   $this->setDirFilesVersion( $this->path );
  }else if(is_file($this->path)){
   $this->setFileVersion( $this->path );
  }else{
   $this->error('error path');
  }
 }
 /**
  * 添加版本
  */
 public function replace(){
  $this->dealFlag = 'replace';
  $this->run();
  echo 'replace success';
 }
 /**
  * 清除版本
  */
 public function clean(){
  $this->dealFlag = 'clean';
  $this->run();
  echo 'clean success';
 }
 protected function success(){
 }
 protected function error($errorMsg){
  echo $errorMsg;
  exit();
 }
 protected function setDirFilesVersion($dir){
  $handle = null;
  $file  = null;
  if ( $handle = opendir($dir)) {
   while ( false !== ($file = readdir($handle)) ) {
    if ($file === '.' || $file === '..' || strpos($file, '.') === -1 ) {continue;}
    $this->setFileVersion($file);
   }
  }
 }
 protected function setFileVersion($file){
  $temp = null;
  /*$pattern = '/<script.*&#63;src=\"(.*&#63;)(\&#63;.*&#63;|\&#63;)&#63;\".*&#63;><\/script>/';*/
  $temp = explode('.', $file) ;
  if ( ! $this->isNeedReplacePostFix(array_pop( $temp )) ) {return;}
  $content = null;
  $content = file_get_contents($file);
  $content = preg_replace_callback('/<script.*&#63;><\/script>/', array(&$this, 'callbackScript'), $content);
  $content = preg_replace_callback('/<link.*&#63;type="text\/css".*&#63;>/', array(&$this, 'callbackCss'), $content);
  // highlight_string($content);
  file_put_contents($file, $content);
 }
 /**
  * 获得版本
  * @param mixed $configs array( 'versionName' : 'version') || $versionName
  */
 protected function setVersion($configs){
  // last_wap_version  = '3-0-0', 
  // wap_version = '3-0-1',
  if (is_array($configs) && $configs > 0) {
   foreach ($configs as $key => $value) {
    $this->version = $value;
    $this->versionName = $key;
   }
  }else if(is_string($configs) && $configs != ''){
   $configs = explode(',', $configs);
   $this->versionName = $configs[0];
   count($configs) == 2 && ($this->version = $configs[1]);
  }else{
   $this->error('the version is empty');
  }
 }
 /**
  * 通过后缀判断该文件是否要添加或清除版本
  * @param string $profix 后缀
  * @return boolean  true | false
  */
 protected function isNeedReplacePostFix($profix){
  if (in_array($profix, $this->filePostFixs)) {
   return true;
  }
  return false;
 }
 /**
  * 设置需要操作的后缀
  */
 public function setFilePostFix($profix){
  if (is_array($profix)) {
   count($profix) > 0 && ( $this->filePostFixs = array_merge($this->filePostFixs, $profix) );
  }else if(is_string($profix)){
   $this->filePostFixs[] = $profix;
  }
 }
}

使用:

$dir  = __DIR__;
$is_clean = false;
//$is_clean = true;
//第一个参就是版本信息, 第二个就是要匹配的文件后缀, 第三个是要匹配的目录或者文件
if ($is_clean) {//清除版本
 $configs = 'eslc-wap';
 $replaceObj = new ReplaceVersion($configs, array('html'), $dir);
 $replaceObj->clean();
}else{//添加或替换版本
 $configs = array('eslc-wap' => '1.0.1');//也可以写成 $configs = 'eslc-wap, 1.0.1';
 $replaceObj = new ReplaceVersion($configs, array('html'), $dir);
 $replaceObj->replace();
}

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP和Python:解釋了不同的範例PHP和Python:解釋了不同的範例Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP和Python:深入了解他們的歷史PHP和Python:深入了解他們的歷史Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

在PHP和Python之間進行選擇:指南在PHP和Python之間進行選擇:指南Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP和框架:現代化語言PHP和框架:現代化語言Apr 18, 2025 am 12:14 AM

PHP在現代化進程中仍然重要,因為它支持大量網站和應用,並通過框架適應開發需求。 1.PHP7提升了性能並引入了新功能。 2.現代框架如Laravel、Symfony和CodeIgniter簡化開發,提高代碼質量。 3.性能優化和最佳實踐進一步提升應用效率。

PHP的影響:網絡開發及以後PHP的影響:網絡開發及以後Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型?Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP如何處理對象克隆(克隆關鍵字)和__clone魔法方法?PHP如何處理對象克隆(克隆關鍵字)和__clone魔法方法?Apr 17, 2025 am 12:24 AM

PHP中使用clone關鍵字創建對象副本,並通過\_\_clone魔法方法定制克隆行為。 1.使用clone關鍵字進行淺拷貝,克隆對象的屬性但不克隆對象屬性內的對象。 2.通過\_\_clone方法可以深拷貝嵌套對象,避免淺拷貝問題。 3.注意避免克隆中的循環引用和性能問題,優化克隆操作以提高效率。

PHP與Python:用例和應用程序PHP與Python:用例和應用程序Apr 17, 2025 am 12:23 AM

PHP適用於Web開發和內容管理系統,Python適合數據科學、機器學習和自動化腳本。 1.PHP在構建快速、可擴展的網站和應用程序方面表現出色,常用於WordPress等CMS。 2.Python在數據科學和機器學習領域表現卓越,擁有豐富的庫如NumPy和TensorFlow。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中