php - 如何将所有相对图像路径替换为绝对路径形式的 css

标签 php css

我想将所有相对背景图像路径替换为绝对路径。在尝试了这么多时间之后,我没能解决这个问题。我当前的代码只解决了最后一个图像路径。我在此代码中使用了路径解析器函数(来自此引用:url_to_absolute())。

<?php

require './url_to_absolute.php';
$css = "
    .selector1{
        background-image:url(../dir1/images/image.jpg);
        width:100%;
    }
    .selector2{
        background-image:url(\"../dir1/images/image2.jpg\");
        color:black;
    }
    .selector3{
        background-image:url( 'dir1/images/image3.jpg' );
        text-align:left;
    }
    .selector4{
        background-image:url( \"dir1/images/image4.jpg\" );
        text-align:left;
    }           
" ;
$base_url = 'http://www.example.com/'; 

$pattern  = "/(?<=\()(.*?)(?=\))/s";
preg_match_all($pattern, $css, $matches);

foreach($matches[1] as $url){
        $url = trim($url);
        $url = str_replace("\"", "", $url);
        $url = str_replace("'", "", $url);
        $full_path = url_to_absolute($base_url, $url);
        $new_css = str_replace($url, $full_path, $css);     
}
print $new_css;

?>

它生成结果 -

.selector1{ background-image:url(../dir1/images/image.jpg); width:100%; } 
.selector2{ background-image:url("../dir1/images/image2.jpg"); color:black; } 
.selector3{ background-image:url( 'dir1/images/image3.jpg' ); text-align:left; } 
.selector4{ background-image:url( "http://www.example.com/dir1/images/image4.jpg" ); text-align:left; } 

请多多指教。

最佳答案

虽然我很欣赏公认的聪明答案,但它可能是我在 PHP 中看到的最复杂的函数之一......

这个如果更容易掌握(根据您的需要调整正则表达式):

function urlsToAbsolute($baseUrl, $html) {

    preg_match_all('/(href="|src=")([^"#]+)(")/i', $html, $matches);

    foreach ($matches[2] as $num => $match) {
        $codec[$match] = url_to_absolute($baseUrl, $match);
    }

    return strtr($html, $codec);
}

关于php - 如何将所有相对图像路径替换为绝对路径形式的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12249943/

相关文章:

php - 再次在 wordpress 中添加自定义背景图像

php - 传单,来自 mysql 的制造商未显示

php - 如何在 PHP 中使用 PDO 获取结果数组?

php - 我怎样才能让这个 div 在 IE8 中扩展并溢出它的容器?

html - 如何在 Vuejs 中使用路由 View 作为选项卡?

css - 9 列的默认布局

css - 非法嵌套 : Nothing may be nested beneath import directives

PHP Image Zoom - 指数级

php - symfony2 中 Avalanche-imagine 的问题

HTML Head 元素未在 w3.org 验证器上正确注册?