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('https://example.com'); // Get the webpage content
$pattern = '/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>/si'; // 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 . "\n";
}