Skip to content
PHP Logo

How can regular expressions be used effectively to manipulate URLs in PHP?

Regular expressions can be used effectively in PHP to manipulate URLs by matching specific patterns within the URL string. This can be useful for tasks such as extracting specific parts of the URL (e.g., the domain, path, query parameters), validating URLs, or transforming URLs into a different format. By using regular expressions, you can create flexible and powerful URL manipulation functions in PHP.

php
// Example: Extracting the domain from a URL using regular expressions
$url = "https://www.example.com/page?param=value";
preg_match('/^(?:https?:\/\/)?(?:www\.)?([^\/?]+)/i', $url, $matches);
$domain = $matches[1];
echo $domain; // Output: example.com