在 Web 開發中,經常需要從 HTML 字符串中提取或過濾外部連結。本文將詳細介紹如何使用 PHP 正則表達式高效提取 <a href="..."> 標籤中的連結地址,並提供實用的代碼範例與進階技巧。
針對 <a> 標籤的 href 屬性,推薦使用以下正則模式:
$preg = '/<a .*?href="(.*?)".*?>/is';
模式解析:
i:忽略大小寫,匹配 <A> 或 <a>s:單行模式,讓 . 也能匹配換行符.*?:非貪婪匹配任意字符,確保精準捕獲屬性值<?php
$preg = '/<a .*?href="(.*?)".*?>/is';
$str = '<a href="鏈接1">URLNAME</a>文本段1<a href="鏈接2" target="_blank">URLNAME</a>文本段2<a target="_blank" href="鏈接3">URLNAME</a>...文本段n';
preg_match_all($preg, $str, $match);
for ($i = 0; $i < count($match[1]); $i++) {
echo $match[1][$i] . "<br />";
}
?>
輸出結果:
鏈接1<br />鏈接2<br />鏈接3<br />
同理可推廣至圖片連結提取,以下為實用範例:
<?php
$str = '<p style="padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 200%;"><img border="0" src="upfiles/2009/07/1246430143_4.jpg" alt=""/></p><p style="padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 200%;"><img border="0" src="upfiles/2009/07/1246430143_3.jpg" alt=""/></p><p style="padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 200%;"><img border="0" src="upfiles/2009/07/1246430143_1.jpg" alt=""/></p>';
$pattern = '/<[img|IMG].*?src=[\'|"](.*?(?:\.gif|\.jpg))[\'|"].*?[\/]?>/';
preg_match_all($pattern, $str, $match);
print_r($match);
?>
DOMDocument + DOMXPath,更健壯且符合標準urlencode/urldecode 配合使用掌握這些技巧,能讓你在爬蟲開發、內容過濾、鏈接檢測等場景中遊刃有餘。