Regular expressions can be used to match hyperlinks within HTML; here is an example code:
$html = '<html><body><a href="https://www.example.com">Example</a></body></html>';
// 匹配所有的 a 标签
preg_match_all('/<a[^>]+href="([^"]*)"[^>]*>(.*)<\/a>/siU', $html, $matches);
// 输出匹配结果
print_r($matches[1]); // 输出所有链接的 URL
print_r($matches[2]); // 输出所有链接的文本内容Explain this regular expression:
<aMatches the starting tag of an `a` tag.[^>]+Match the attributes of an `a` tag until>Until symbolhref="([^"]*)"Matches the value of the `href` attribute; use.[^"]*Indicates that it can match an arbitrary number of non-quotation-mark characters.[^>]*Matches other attributes of an `a` tag; use.*Indicates that zero or more non-instances can be matched.>character>(.*)<\/a>Matches the end tag and text content of an `a` tag; use..*Indicates that it can match an arbitrary number of characters; use.UThe modifier indicates a greedy match, preventing the system from matching the text content of multiple <a> tags.
Please note that using regular expressions to match HTML is not a perfect solution, as HTML can have various formats and complex scenarios may occasionally arise. A better approach is to use a dedicated HTML parser—such as PHP's DOM parser or the Simple HTML DOM parser—to process HTML content.