In HTML, links are typically written as <a> The tag appears in this form. href The attribute specifies the link address. You can use regular expressions to match it. <a> Tag and extract its contents. href Attribute value. Here is an example regular expression:
$pattern = '/<a\s[^>]*href=([\'"])(.*?)\1[^>]*>/i';This regular expression matches all. <a> Tag and extract its contents. href Attribute value. Here,([\'"]) Indicates matching quotation marks (single or double quotation marks),\1 Indicates the reference to the first captured group (i.e., the matched quotation mark).(.*?) Represents a non-greedy match of any character until the next quotation mark is encountered.
Here is an example code snippet:
// 获取目标 URL 的 HTML 内容
$html = file_get_contents('https://example.com');
// 匹配所有链接
$pattern = '/<a\s[^>]*href=([\'"])(.*?)\1[^>]*>/i';
if (preg_match_all($pattern, $html, $matches)) {
// 提取链接地址
$links = $matches[2];
foreach ($links as $link) {
echo $link . '<br>';
}
} else {
echo '没有找到链接';
}In the above code, we first retrieve the HTML content of the target URL, then use a regular expression to match all links within that content. If the match is successful, we extract the link addresses from the match results and output them; otherwise, we output "No links found."