What are the advantages of using regex or explode to extract specific parts of a URL in PHP?

When working with URLs in PHP, you may need to extract specific parts such as the domain, path, or query parameters. Two common methods to achieve this are using regular expressions (regex) or the explode function. Using regex allows for more flexibility and precision in pattern matching, making it suitable for complex URL structures. On the other hand, explode is simpler and more straightforward for basic extraction tasks. Here is an example of using regex to extract the domain from a URL in PHP:

$url = "https://www.example.com/path/to/page?query=123";
preg_match('/^(?:https?:\/\/)?(?:www\.)?([^\/]+)/i', $url, $matches);
$domain = $matches[1];
echo $domain; // Output: example.com