How can regex be used to extract all links from a webpage in PHP?

To extract all links from a webpage in PHP using regex, you can use the preg_match_all function with a regex pattern that matches URLs. The regex pattern should look for the href attribute within anchor tags (<a>) and extract the URL within the quotes. Once the URLs are extracted, you can store them in an array for further processing.

$html = file_get_contents(&#039;https://example.com&#039;); // Get the webpage content
$pattern = &#039;/&lt;a\s[^&gt;]*href=(\&quot;??)([^\&quot; &gt;]*?)\\1[^&gt;]*&gt;/si&#039;; // Regex pattern to match URLs within anchor tags
preg_match_all($pattern, $html, $matches); // Extract all URLs using regex
$links = $matches[2]; // Store the extracted URLs in an array

// Output the extracted links
foreach ($links as $link) {
    echo $link . &quot;\n&quot;;
}