如何用PHP替换CSS中本地background-image的URL,保留外部链接?
Fixing CSS Background-Image URL Replacement: Target Only Local Links
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
- Regex Matching: The regex
/url\(["\']?([^"\')]+)["\']?\)/icatches all validurl()formats in CSS—whether they use double quotes, single quotes, or no quotes at all. It captures the actual URL inside the parentheses. - External Link Check: The
isexternalfunction usesparse_urlto check if the URL has a host that's not your domain. Make sure to replaceexample.comwith your actual website domain! - 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")→ Becomesurl("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
相关产品推荐
相关产品推荐

