You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP替换CSS中本地background-image的URL,保留外部链接?

Let's solve this problem where your current code replaces all URLs in CSS background-image declarations, but you need to leave external links untouched and only modify local ones.

The Problem with Your Current Code

Your existing str_replace approach works globally—it adds the prefix to every url(" occurrence, regardless of whether the link is local (like images/bg2.jpg) or external (like https://example.com/bg1.jpg). We need to add logic to distinguish between the two.

Solution: Use Regex + Callback with Your isexternal Function

We'll leverage preg_replace_callback to match each url() in the CSS, check if it's an external link using your existing function, and only modify local URLs. Here's the revised code:

// Your existing external link check function (updated for clarity)
function isexternal($url) {
    $components = parse_url($url);
    // Replace 'example.com' with YOUR actual domain to correctly flag external links
    return !empty($components['host']) && strcasecmp($components['host'], 'example.com') !== 0;
}

$file = 'path/to/your/style.css';
$stringToAdd = 'somefolder/'; // The prefix you want to add to local URLs

// Read the CSS file
$css = file_get_contents($file);

// Process each url() declaration
$css = preg_replace_callback(
    // Regex to match url() with optional quotes (handles all common CSS syntax)
    '/url\(["\']?([^"\')]+)["\']?\)/i',
    function($matches) use ($stringToAdd) {
        $targetUrl = $matches[1];
        
        // If it's an external link, return it as-is
        if (isexternal($targetUrl)) {
            return 'url("' . $targetUrl . '")';
        }
        
        // If local, prepend the desired string
        return 'url("' . $stringToAdd . $targetUrl . '")';
    },
    $css
);

// Save the modified CSS back to the file
file_put_contents($file, $css);

How This Works

  1. Regex Matching: The regex /url\(["\']?([^"\')]+)["\']?\)/i catches all valid url() formats in CSS—whether they use double quotes, single quotes, or no quotes at all. It captures the actual URL inside the parentheses.
  2. External Link Check: The isexternal function uses parse_url to check if the URL has a host that's not your domain. Make sure to replace example.com with your actual website domain!
  3. Conditional Replacement: For each matched URL, we either leave it untouched (if external) or add your prefix (if local).

Example Result

  • Original local URL: url("images/bg2.jpg") → Becomes url("somefolder/images/bg2.jpg")
  • Original external URL: url("https://example.com/bg1.jpg") → Stays exactly the same

Notes

  • If your CSS has edge cases (like URLs containing parentheses or quotes, which are rare in valid CSS), you may need to tweak the regex, but this should handle 99% of common scenarios.
  • Always back up your CSS file before running batch modifications!

内容的提问来源于stack exchange,提问作者wyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:20:49