1. 引言
2. PHP正则表达式基础
在开始之前,我们需要了解一些PHP正则表达式的基础知识。PHP中用于正则表达式的函数是preg_match、preg_match_all、preg_replace等。下面是一些基本概念:
- 字符匹配:
.匹配除换行符以外的任意字符。 - 字符集:
[]定义字符集,例如[a-z]匹配任意小写字母。 - 范围:
[a-z]等价于[a-z]。 - 量词:
*匹配前面的子表达式零次或多次。 - 选择:
|表示逻辑或。
3. 提取图片地址
$pattern = '/<img\s+src="([^"]+)"\s*/';
这个正则表达式的含义如下:
<img\s+匹配<img后面跟一个或多个空格。src="匹配src="字符串。([^"]+)匹配并捕获一个或多个非引号字符(即图片地址)。"\s*/匹配"字符、一个或多个空格,以及闭合的图片标签。
4. 实战技巧
4.1 处理多个图片
$html = '<img src="http://example.com/image1.jpg" alt="Image 1"><img src="http://example.com/image2.jpg" alt="Image 2">';
preg_match_all($pattern, $html, $matches);
print_r($matches[1]); // 输出所有图片地址
4.2 考虑HTML编码
$encodedUrl = 'http://example.com/image%20name.jpg';
$decodedUrl = html_entity_decode($encodedUrl);
4.3 替换图片地址
$pattern = '/<img\s+src="([^"]+)"\s*/';
$replacement = '<img src="http://newdomain.com/1$1" alt="$2" />';
$newHtml = preg_replace($pattern, $replacement, $html);