在 PHP 開發中,從字串中識別、提取或過濾 HTML 超連結是常見需求。本文將系統介紹如何使用正則表達式實現連結檢測、URL 提取與標籤移除,並提供可直接套用的程式碼範例。
最簡單的做法是使用 preg_match() 搭配針對 <a> 標籤的正則模式:
<?php
$str = "ssdsf<a target='_blank' href='https://www.example.com/' >sdf</a>sdfss";
if (preg_match("/<a\s+href=[^>]*>|<\/\s*a[^>]*>/i", $str)) {
echo "該字串包含超連結";
} else {
echo "該字串不包含超連結標記";
}
?>
模式解析:<a\s+href=[^>]*> 匹配開始標籤,<\/\s*a[^>]*> 匹配結束標籤,i 修飾符忽略大小寫。
利用「正向後顧」(?<=href=) 與「正向前顧」(?=>) 可精準鎖定 URL 部分:
<?php
$html = "<a href='www.example.com'>點我</a><a href='www.test.com'>看這裡</a>";
// 將所有 href 值替換為 #,達到移除連結效果
$result = preg_replace("/(?<=href=)([^>]*)(?=>)/i", "#", $html);
echo $result;
// 輸出:<a href='#'>點我</a><a href='#'>看這裡</a>
?>
(?<=exp):匹配 exp 之後的位置(不消耗字元)(?=exp):匹配 exp 之前的位置href= 之後、> 之前的所有非 > 字元以下函式可一次性解析文檔中所有 <a> 標籤,回傳結構化陣列:
<?php
function match_links($document) {
// 使用 'isx' 修飾符:i=忽略大小寫、s=單行模式、x=擴展語法(可加註解)
preg_match_all(
"'<\s*a\s.*?href\s*=\s*(['\"])(?(1)(.*?)\1|([^\s>]+))[^>]*>(.*?)</a>'isx",
$document,
$links
);
$match = ['link' => [], 'content' => [], 'all' => []];
// $links[2] 為帶引號的 URL,$links[3] 為不帶引號的 URL
foreach (array_merge($links[2], $links[3]) as $val) {
if (!empty($val)) $match['link'][] = $val;
}
foreach ($links[4] as $val) {
if (!empty($val)) $match['content'][] = $val;
}
foreach ($links[0] as $val) {
if (!empty($val)) $match['all'][] = $val;
}
return $match;
}
// 使用範例
$html = "<a href='https://a.com'>站點A</a> 中間文字 <a href=https://b.com>站點B</a>";
print_r(match_links($html));
/*
Array
(
[link] => Array ( [0] => https://a.com [1] => https://b.com )
[content] => Array ( [0] => 站點A [1] => 站點B )
[all] => Array ( [0] => <a href='https://a.com'>站點A</a> [1] => <a href=https://b.com>站點B</a> )
)
*/
?>
DOMDocument + DOMXPath 解析,容錯率更高。preg_match_all 一次性提取,避免重複匹配。掌握上述技巧,即可在 PHP 專案中靈活處理超連結相關需求,無論是內容審核、資料清洗還是 SEO 分析都能得心應手。