引言
准备工作
在开始之前,请确保你的环境中已安装PHP,并且已经配置好了相应的开发环境。
步骤一:提取CSS内容
首先,我们需要从HTML页面中提取出CSS内容。这可以通过分析HTML结构来实现。以下是一个简单的示例代码:
<?php
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url('http://example.com/background.jpg');
}
</style>
</head>
<body>
<h1>Example</h1>
</body>
</html>
HTML;
$css = preg_match('/<style>(.*?)<\/style>/s', $html, $matches) ? $matches[1] : '';
?>
在这段代码中,我们使用preg_match
函数来查找<style>
标签内的内容。<style>
标签内的内容就是我们要分析的CSS。
步骤二:提取图片链接
<?php
$pattern = '/url\((\'|")?(.*?)\1\)/';
$images = array();
if (preg_match_all($pattern, $css, $matches)) {
foreach ($matches[2] as $match) {
if (strpos($match, 'http') === 0 || strpos($match, '/') === 0) {
$images[] = $match;
} else {
$images[] = 'http://' . $_SERVER['HTTP_HOST'] . $match;
}
}
}
?>
步骤三:输出结果
<?php
if (!empty($images)) {
echo "Found " . count($images) . " images:\n";
foreach ($images as $image) {
echo $image . "\n";
}
} else {
echo "No images found.";
}
?>