dselp3944
dselp3944
2010-02-11 11:06

正则表达式,用于在HTML文档中为.js和.css引用添加版本号

  • reference
  • regex
  • replace
  • php
  • html

I have a HTML document where I want to automatically have a version number added to all script and style sheet references.

the following should be replaced

 <link ... href="file.css" media="all" />
 <script ... src="file.js"></script>
 <script ... src="http://myhost.com/file.js"></script>

with that

<link ... href="file.v123456.css" media="all" />
<script ... src="file.v123456.js"></script>
<script ... src="http://myhost.com/file.v123456.js"></script>

where 123456 is my dynamic version number.

But it shoud ONLY do that on local files

<link ... href="http://otherhost.com/file.css" media="all" />

should be left untouched.

So far I have the following regex:

$html = preg_replace('#(src|href)=("|\')(?!http)(?!("|\'| |\+))(.*)\.(css|js|swf)("|\')#Ui', '\\1=\\2\\3\\4.v'.$version .'.\\5\\6', $html);

But it does not work 100% and I am sure that there is a better way in doing this. How would you write it?

Edit:

I have it now using DOMDocument, but it turns out that it's pretty slow!

    <?php
//------- snip --------------
            $host       = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
            $refs       = array();
            $version    = "v". $version;
            $doc        = new DOMDocument();        
            $tmpDoc     = $html;

            $doc->loadHTML($tmpDoc);        
            $xpath = new DOMXPath($doc);
            foreach($xpath->query('/html/head/link/@href') as $href) {
                $ref = $href->value;
                if(
                    !preg_match('/^https?:/', $ref) || 
                    strpos($ref, $host) === 0               
                ) {
                    $refs[$ref] = preg_replace('/\.css$/', '.'.$version.'$0', $ref);
                }
            }
            foreach ($xpath->query('//script/@src') as $src) {
                $ref = $src->value;
                if(
                    !preg_match('/^https?:/', $ref) ||
                    strpos($ref, $host) === 0
                ) {
                    $refs[$ref] = preg_replace('/\.js$/', '.'.$version.'$0', $ref);
                }
            }       
            $html = str_replace(
                        array_keys($refs), 
                        array_values($refs), 
                        $tmpDoc
                    );
//------- snip --------------
    ?>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐