PHP 正则表达式匹配 A 标签链接:高效提取 href 属性值
以下是匹配 a 链接的正则表达式:
$pattern = '/<a\s+(?:[^>]*?\s+)?href=(['"])(.*?)\1/';
该表达式匹配一个以<a开头,以>结尾的标签,并在其中匹配href属性的值。可以使用preg_match_all()函数来执行匹配操作:
$str = '<a href="http://www.example.com">Example</a><a href='http://www.google.com'>Google</a>';
$pattern = '/<a\s+(?:[^>]*?\s+)?href=(['"])(.*?)\1/';
if (preg_match_all($pattern, $str, $matches)) {
print_r($matches[2]);
}
输出结果为:
Array
(
[0] => http://www.example.com
[1] => http://www.google.com
)
可以看到,该正则表达式成功地匹配了两个 a 链接的href属性值。
原文地址: https://www.cveoy.top/t/topic/lKty 著作权归作者所有。请勿转载和采集!