Skip to content

Instantly share code, notes, and snippets.

@muratpurc
Created November 5, 2011 10:08
Show Gist options
  • Save muratpurc/1341358 to your computer and use it in GitHub Desktop.
Save muratpurc/1341358 to your computer and use it in GitHub Desktop.
PHP/CSS: Extract all url definitions (e. g. background images) in CSS declarations
/**
* Extracts all url definitions (e. g. urls to background images) in CSS.
*
* This snippet could be usefull within a build process where css files are
* distributed in different folder during development and should be merged together.
* Existing url definitions could be invalid in some cases.
*/
// example css content, could be read from a file
$cssFileContent = <<<CSS
/* background image url without quotes */
div.myBg {
background-image: url(../images/bg.gif);
background-color: orange;
}
/* background image url with double quotes */
p.success {
background: green url("images/bg.gif") fixed no-repeat;
}
/* background image url with double quotes and spaces */
p.success2 {
background-image: green url( "images/bg.gif" );
}
/* external url to a webfont with single quotes, example from http://www.google.com/webfonts */
@font-face {
font-family: 'Rammetto One';
font-style: normal;
font-weight: 400;
src: local('Rammetto One Regular'), local('RammettoOne-Regular'),
url('http://themes.googleusercontent.com/static/fonts/rammettoone/v1/mh0uQ1tV8QgSx9v_KyEYPHhCUOGz7vYGh680lGh-uXM.woff') format('woff');
}
CSS;
// matches all url definitions inside the css file as follows:
// url("*") URL definitions with double quotes
// url('*') URL definitions with single quotes
// url(*) URL definitions without quotes
preg_match_all('/url\(([\s])?([\"|\'])?(.*?)([\"|\'])?([\s])?\)/i', $cssFileContent, $matches, PREG_PATTERN_ORDER);
// in case of found matches, the multi-dimensional array $matches contains following
// important entries:
// $matches[0] (array) List containing each string matching the full pattern, e. g. url("images/bg.gif")
// $matches[3] (array) List containing matched url definitions, e. g. images/bg.gif
if ($matches) {
foreach($matches[3] as $match) {
// do whatever you want with those matches, adapt paths by changing them to absolute or CDN paths
// - "images/bg.gif" -> "/path_to_css_module/images/bg.gif"
// - "images/bg.gif" -> "http://cdn.domain.tld/path_to_css_module/images/bg.gif"
echo $match . "<br/>";
}
}
@FlashT
Copy link

FlashT commented Jan 9, 2018

but why to match things that are not used? just removed the unnecessary brackets, so it would be $matches[1] not $matches[3] - now it's a waste of memory and waste of computing power

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment