<?php
$str = "ssdsf<a target='_blank' href='https://www.example.com/' >sdf</a>sdfss";
if (preg_match('/<a\s+href=[^>]*>/i', $str)) {
echo "包含超鏈接標記";
} else {
echo "無超鏈接標記";
}
正則解析: <a\s+href=[^>]*> 匹配 <a 後跟空白、href=、任意非 > 字符、最後 >。i 忽略大小寫。
<?php
$html = "<a href='www.example.com'>鏈接1</a><a href='www.test.com'>鏈接2</a>";
// 正則:(?<=href=) 正向後顧斷言,匹配 href= 之後
// ([^>]*) 捕獲組:任意非 > 字符
// (?=>) 正向前顧斷言,匹配 > 之前
$pattern = '/(?<=href=)([^>]*)(?=>)/i';
// 替換為 #(去除所有鏈接)
echo preg_replace($pattern, '#', $html);
// 輸出:<a href='#'>鏈接1</a><a href='#'>鏈接2</a>
// 提取所有鏈接地址
preg_match_all($pattern, $html, $matches);
print_r($matches[1]);
/*
Array
(
[0] => 'www.example.com'
[1] => 'www.test.com'
)
*/
<a> 標簽信息(URL + 鏈接文本)<?php
function match_links(string $document): array {
// 正則詳解:
// '<\s*a\s.*?href\s*=\s*([\'"])? # (組3)
// [^>]*> # 剩餘屬性直到 >
// (.*?) # 鏈接文本(組4),非貪婪
// </a>'isx # 結束標簽,i忽略大小寫 s單行模式 x忽略空白
$pattern = '<\s*a\s.*?href\s*=\s*([\'"])?(?(1)(.*?)\1|([^\s>]+))[^>]*>?(.*?)</a>';
preg_match_all($pattern, $document, $links);
$result = ['link' => [], 'content' => [], 'all' => []];
// 組2:帶引號的 URL
foreach ($links[2] as $val) {
if ($val !== '') $result['link'][] = $val;
}
// 組3:不帶引號的 URL
foreach ($links[3] as $val) {
if ($val !== '') $result['link'][] = $val;
}
// 組4:鏈接文本
foreach ($links[4] as $val) {
if ($val !== '') $result['content'][] = trim($val);
}
// 組0:完整標簽
foreach ($links[0] as $val) {
if ($val !== '') $result['all'][] = $val;
}
return $result;
}
// 測試
$html = '<a href="https://a.com">站點A</a> 中間文字 <a href=\'https://b.com\' class="btn">站點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' class="btn">站點B</a>
)
)
正則處理 HTML 存在邊界情況(屬性換行、單雙引號混用、巢狀標簽)。生產環境推薦用 DOMDocument:
<?php
function extractLinksDom(string $html): array {
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="UTF-8"?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
$text = trim($a->textContent);
if ($href !== '') {
$links[] = ['url' => $href, 'text' => $text];
}
}
return $links;
}
S (study) 修飾符:/pattern/Is,預編譯正則加速重複匹配。.* 跨行匹配。XMLReader 流式解析。