How can regular expressions like preg_match_all be effectively used in PHP to filter URLs that belong to a specific domain?

To filter URLs that belong to a specific domain using regular expressions in PHP, you can use preg_match_all to match URLs with the desired domain. By defining a regex pattern that matches the domain you want to filter, you can extract the URLs that belong to that domain from a given text or array of URLs.

<?php
// Define the domain you want to filter
$domain = 'example.com';

// Define the text containing URLs
$text = 'Visit us at http://example.com, or check out http://anotherdomain.com';

// Define the regex pattern to match URLs with the specified domain
$pattern = '/\bhttps?:\/\/(?:www\.)?' . preg_quote($domain, '/') . '\b/';

// Match URLs with the specified domain using preg_match_all
preg_match_all($pattern, $text, $matches);

// Output the matched URLs
print_r($matches[0]);
?>