一、解析图片src
属性
<img src="http://example.com/images/photo.jpg" alt="Sample Image">
为了解析这样的src
属性,我们可以使用PHP的正则表达式函数。
1.1 准备正则表达式
$regex = '/<img\s+[^>]*src="([^"]+)"[^>]*>/';
这个正则表达式的工作原理如下:
<img\s+[^>]*src="
: 匹配以<img
开头,后跟一个或多个空白字符,然后是src="
。([^"]+)
: 匹配并捕获一个或多个不是双引号的字符,直到遇到第一个双引号。"[^>]*>
: 匹配双引号,后跟零个或多个不是>
的字符,直到遇到第一个>
。
1.2 使用正则表达式解析
$html = <<<HTML
<img src="http://example.com/images/photo.jpg" alt="Sample Image">
<img src="http://example.com/another_image.jpg" alt="Another Image">
HTML;
preg_match_all($regex, $html, $matches);
foreach ($matches[1] as $match) {
echo "Found image src: $match\n";
}
这段代码将输出:
Found image src: http://example.com/images/photo.jpg
Found image src: http://example.com/another_image.jpg
二、修改图片src
属性
2.1 更改图片路径
$regex = '/<img\s+[^>]*src="([^"]+)"[^>]*>/';
$replacement = '<img $1 src="https://secure.example.com/$2">';
$html = <<<HTML
<img src="http://example.com/images/photo.jpg" alt="Sample Image">
<img src="http://example.com/another_image.jpg" alt="Another Image">
HTML;
$html = preg_replace($regex, $replacement, $html);
echo $html;
这段代码将输出:
<img src="https://secure.example.com/images/photo.jpg" alt="Sample Image">
<img src="https://secure.example.com/another_image.jpg" alt="Another Image">
2.2 动态添加查询参数
$regex = '/<img\s+[^>]*src="([^"]+)"[^>]*>/';
$replacement = '<img $1 src="$2?param=value">';
$html = <<<HTML
<img src="http://example.com/images/photo.jpg" alt="Sample Image">
HTML;
$html = preg_replace($regex, $replacement, $html);
echo $html;
这段代码将输出:
<img src="http://example.com/images/photo.jpg?param=value" alt="Sample Image">