要匹配a标签的href属性值,可以使用以下正则表达式:
$pattern = '/<a\s+[^>]*href=["\']?([^"\'>]+)["\']?[^>]*>/i';
这个正则表达式的含义是:
<a:匹配以<a开头的字符串\s+:匹配一个或多个空白字符(包括空格、制表符等)[^>]*:匹配0个或多个非>字符href=["\']?:匹配href属性的开始部分,可能包含一个单引号或双引号([^"\'>]+):匹配一个或多个非", ', >字符,这个部分就是我们要匹配的href属性值["\']?:匹配href属性的结束部分,可能包含一个单引号或双引号[^>]*:匹配0个或多个非>字符>:匹配>字符,表示a标签的结束使用preg_match_all函数可以进行匹配,示例代码如下:
$html = '<a href="http://example.com">Link 1</a> <a href=\'https://www.example.org\'>Link 2</a>';
$pattern = '/<a\s+[^>]*href=["\']?([^"\'>]+)["\']?[^>]*>/i';
preg_match_all($pattern, $html, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $match) {
echo $match . "\n";
}
}
输出结果为:
http://example.com
https://www.example.org
这样就可以提取出a标签的href属性值了。
下一篇:php strpos
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站