• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php实现压缩多个CSS与JS文件的方法_php技巧

php 搞代码 4年前 (2022-01-26) 46次浏览 已收录 0个评论

本文实例讲述了php实现压缩多个CSS与JS文件的方法。分享给大家供大家参考。具体实现方法如下:

1. 压缩css

<?php    <br />header('Content-type: text/css');    <br />ob_start("compress");    <br />function compress($buffer) {    <br />    /* remove comments */    <br />    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);    <br />    /* remove tabs, spaces, newlines, etc. */    <br />    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);    <br />    return $buffer;    <br />}      <br />    <br />/* your css files */    <br />include('galleria.css');    <br />include('articles.css');    <br />    <br />ob_end_flush();

使用方法如下:

<link href="compress.php" rel="stylesheet" type="text/css" /><span id="tester">test</span>

2. 压缩js,利用jsmin类:

本实例源自:http://code.google.com/p/minify/

header('Content-type: text/javascript');    <br />require 'jsmin.php';    <br />echo JSMin::minify(file_get_contents('common.js') . file_get_contents('common2.js'));

其中jsmin.php文件如下:

<br /><?php<br />/**<br /> * jsmin.php - PHP implementation of Douglas Crockford's JSMin.<br /> *<br /> * This is pretty much a direct port of jsmin.c to PHP with just a few<br /> * PHP-specific performance tweaks. Also, whereas jsmin.c reads from stdin and<br /> * outputs to stdout, this library accepts a string as input and returns another<br /> * string as output.<br /> *<br /> * PHP 5 or higher is required.<br /> *<br /> * Permission is hereby granted to use this version of the library under the<br /> * same terms as jsmin.c, which has the following license:<br /> *<br /> * --<br /> * Copyright (c) 2002 Douglas Crockford  (www.crockford.com)<br /> *<br /> * Permission is hereby granted, free of charge, to any person obtaining a copy of<br /> * this software and associated documentation files (the "Software"), to deal in<br /> * the Software without restriction, including without limitation the rights to<br /> * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies<br /> * of the Software, and to permit persons to whom the Software is furnished to do<br /> * so, subject to the following conditions:<br /> *<br /> * The above copyright notice and this permission notice shall be included in all<br /> * copies or substantial portions of the Software.<br /> *<br /> * The Software shall be used for Good, not Evil.<br /> *<br /> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br /> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br /> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br /> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br /> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br /> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE<br /> * SOFTWARE.<br /> * --<br /> *<br /> * @package JSMin<br /> * @author Ryan Grove <br /> * @copyright 2002 Douglas Crockford  (jsmin.c)<br /> * @copyright 2008 Ryan Grove  (PHP port)<br /> * @copyright 2012 Adam Goforth  (Updates)<br /> * @license http://opensource.org/licenses/mit-license.php MIT License<br /> * @version 1.1.2 (2012-05-01)<br /> * @link https://github.com/rgrove/jsmin-php<br /> */<br />class JSMin {<br />  const ORD_LF            = 10;<br />  const ORD_SPACE         = 32;<br />  const ACTION_KEEP_A     = 1;<br />  const ACTION_DELETE_A   = 2;<br />  const ACTION_DELETE_A_B = 3;<br />  protected $a           = '';<br />  protected $b           = '';<br />  protected $input       = '';<br />  protected $inputIndex  = 0;<br />  protected $inputLength = 0;<br />  protected $lookAhead   = null;<br />  protected $output      = '';<br />  // -- Public Static Methods --------------------------------------------------<br />  /**<br />   * Minify Javascript<br />   *<br />   * @uses __construct()<br />   * @uses min()<br />   * @param string $js Javascript to be minified<br />   * @return string<br />   */<br />  public static function minify($js) {<br />    $jsmin = new JSMin($js);<br />    return $jsmin->min();<br />  }<br />  // -- Public Instance Methods ------------------------------------------------<br />  /**<br />   * Constructor<br />   *<br />   * @param string $input Javascript to be minified<br />   */<br />  public function __construct($input) {<br />    $this->input       = str_replace("\r\n", "\n", $input);<br />    $this->inputLength = strlen($this->input);<br />  }<br />  // -- Protected Instance Methods ---------------------------------------------<br />  /**<br />   * Action -- do something! What to do is determined by the $command argument.<br />   *<br />   * action treats a string as a single character. Wow!<br />   * action recognizes a regular expression if it is preceded by ( or , or =.<br />   *<br />   * @uses next()<br />   * @uses get()<br />   * @throws JSMinException If parser errors are found:<br />   *         - Unterminated string literal<br />   *         - Unterminated regular expression set in regex literal<br />   *         - Unterminated regular expression literal<br />   * @param int $command One of class constants:<br />   *      ACTION_KEEP_A      Output A. Copy B to A. Get the next B.<br />   *      ACTION_DELETE_A    Copy B to A. Get the next B. (Delete A).<br />   *      ACTION_DELETE_A_B  Get the next B. (Delete B).<br />  */<br />  protected function action($command) {<br />    switch($command) {<br />      case self::ACTION_KEEP_A:<br />        $this->output .= $this->a;<br />      case self::ACTION_DELETE_A:<br />        $this->a = $this->b;<br />        if ($this->a === "'" || $this->a === '"') {<br />          for (;;) {<br />            $this->output .= $this->a;<br />            $this->a       = $this->get();<br />            if ($this->a === $this->b) {<br />              break;<br />            }<br />            if (ord($this->a) <= self::ORD_LF) {<br />              throw new JSMinException('Unterminated string literal.');<br />            }<br />            if ($this->a === '\\') {<br />              $this->output .= $this->a;<br />              $this->a       = $this->get();<br />            }<br />          }<br />        }<br />      case self::ACTION_DELETE_A_B:<br />        $this->b = $this->next();<br />        if ($this->b === '/' && (<br />            $this->a === '(' || $this->a === ',' || $this->a === '=' ||<br />            $this->a === ':' || $this->a === '[' || $this->a === '!' ||<br />            $this->a === '&' || $this->a === '|' || $this->a === '?' ||<br />            $this->a === '{' || $this->a === '}' || $this->a === ';' ||<br />            $this->a === "\n" )) {<br />          $this->output .= $this->a . $this->b;<br />          for (;;) {<br />            $this->a = $this->get();<br />            if ($this->a === '[') {<br />              /*<br />                inside a regex [...] set, which MAY contain a '/' itself. Example: mootools Form.Validator near line 460:<br />                  return Form.Validator.getValidator('IsEmpty').test(element) || (/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]\.?){0,63}[a-z0-9!#$%&'*+/=?^_`{|}~-]@(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\])$/i).test(element.get('value'));<br />              */<br />              for (;;) {<br />                $this->output .= $this->a;<br />                $this->a = $this->get();<br />                if ($this->a === ']') {<br />                    break;<br />                } elseif ($this->a === '\\') {<br />                  $this->output .= $this->a;<br />                  $this->a       = $this->get();<br />                } elseif (ord($this->a) <= self::ORD_LF) {<br />                  throw new JSMinException('Unterminated regular expression set in regex literal.');<br />                }<br />              }<br />            } elseif ($this->a === '/') {<br />              break;<br />            } elseif ($this->a === '\\') {<br />              $this->output .= $this->a;<br />              $this->a       = $this->get();<br />            } elseif (ord($this->a) <= self::ORD_LF) {<br />              throw new JSMinException('Unterminated regular expression literal.');<br />            }<br />            $this->output .= $this->a;<br />          }<br />          $this->b = $this->next();<br />        }<br />    }<br />  }<br />  /**<br />   * Get next char. Convert ctrl char to space.<br />   *<br />   * @return string|null<br />   */<br />  protected function get() {<br />    $c = $this->lookAhead;<br />    $this->lookAhead = null;<br />    if ($c === null) {<br />      if ($this->inputIndex inputLength) {<br />        $c = substr($this->input, $this->inputIndex, 1);<br />        $this->inputIndex += 1;<br /><div>本文来*源gaodai^.ma#com搞#代!码网</div><pre>搞gaodaima代码

} else {
$c = null;
}
}
if ($c === “\r”) {
return “\n”;
}
if ($c === null || $c === “\n” || ord($c) >= self::ORD_SPACE) {
return $c;
}
return ‘ ‘;
}
/**
* Is $c a letter, digit, underscore, dollar sign, or non-ASCII character.
*
* @return bool
*/
protected function isAlphaNum($c) {
return ord($c) > 126 || $c === ‘\\’ || preg_match(‘/^[\w\$]$/’, $c) === 1;
}
/**
* Perform minification, return result
*
* @uses action()
* @uses isAlphaNum()
* @uses get()
* @uses peek()
* @return string
*/
protected function min() {
if (0 == strncmp($this->peek(), “\xef”, 1)) {
$this->get();
$this->get();
$this->get();
}
$this->a = “\n”;
$this->action(self::ACTION_DELETE_A_B);
while ($this->a !== null) {
switch ($this->a) {
case ‘ ‘:
if ($this->isAlphaNum($this->b)) {
$this->action(self::ACTION_KEEP_A);
} else {
$this->action(self::ACTION_DELETE_A);
}
break;
case “\n”:
switch ($this->b) {
case ‘{‘:
case ‘[‘:
case ‘(‘:
case ‘+’:
case ‘-‘:
case ‘!’:
case ‘~’:
$this->action(self::ACTION_KEEP_A);
break;
case ‘ ‘:
$this->action(self::ACTION_DELETE_A_B);
break;
default:
if ($this->isAlphaNum($this->b)) {
$this->action(self::ACTION_KEEP_A);
}
else {
$this->action(self::ACTION_DELETE_A);
}
}
break;
default:
switch ($this->b) {
case ‘ ‘:
if ($this->isAlphaNum($this->a)) {
$this->action(self::ACTION_KEEP_A);
break;
}
$this->action(self::ACTION_DELETE_A_B);
break;
case “\n”:
switch ($this->a) {
case ‘}’:
case ‘]’:
case ‘)’:
case ‘+’:
case ‘-‘:
case ‘”‘:
case “‘”:
$this->action(self::ACTION_KEEP_A);
break;
default:
if ($this->isAlphaNum($this->a)) {
$this->action(self::ACTION_KEEP_A);
}
else {
$this->action(self::ACTION_DELETE_A_B);
}
}
break;
default:
$this->action(self::ACTION_KEEP_A);
break;
}
}
}
return $this->output;
}
/**
* Get the next character, skipping over comments. peek() is used to see
* if a ‘/’ is followed by a ‘/’ or ‘*’.
*
* @uses get()
* @uses peek()
* @throws JSMinException On unterminated comment.
* @return string
*/
protected function next() {
$c = $this->get();
if ($c === ‘/’) {
switch($this->peek()) {
case ‘/’:
for (;;) {
$c = $this->get();
if (ord($c) <= self::ORD_LF) {
return $c;
}
}
case ‘*’:
$this->get();
for (;;) {
switch($this->get()) {
case ‘*’:
if ($this->peek() === ‘/’) {
$this->get();
return ‘ ‘;
}
break;
case null:
throw new JSMinException(‘Unterminated comment.’);
}
}
default:
return $c;
}
}
return $c;
}
/**
* Get next char. If is ctrl character, translate to a space or newline.
*
* @uses get()
* @return string|null
*/
protected function peek() {
$this->lookAhead = $this->get();
return $this->lookAhead;
}
}
// — Exceptions —————————————————————
class JSMinException extends Exception {}
?>

希望本文所述对大家的php程序设计有所帮助。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php实现压缩多个CSS与JS文件的方法_php技巧

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址