What potential pitfalls should be considered when using preg_replace for URL manipulation in PHP?

When using preg_replace for URL manipulation in PHP, potential pitfalls to consider include the possibility of inadvertently introducing security vulnerabilities such as allowing for code injection or unintentionally modifying valid URLs. To mitigate these risks, it is important to carefully validate and sanitize input data before applying regular expressions to manipulate URLs.

// Example of validating and sanitizing input data before using preg_replace for URL manipulation
$url = $_GET['url'] ?? ''; // Get the URL input from user
if (filter_var($url, FILTER_VALIDATE_URL)) {
    // URL is valid, proceed with manipulation
    $sanitized_url = filter_var($url, FILTER_SANITIZE_URL); // Sanitize the URL
    $manipulated_url = preg_replace('/pattern/', 'replacement', $sanitized_url); // Apply preg_replace
    echo $manipulated_url; // Output the manipulated URL
} else {
    echo 'Invalid URL'; // Handle invalid URL input
}