What are the potential pitfalls of using str_replace for URL manipulation in PHP?
Using str_replace for URL manipulation in PHP can be problematic because it may not handle all edge cases, such as URLs with query strings or special characters. It is better to use built-in functions like parse_url and http_build_url to manipulate URLs safely and accurately.
// Using parse_url and http_build_url for URL manipulation
$url = "https://www.example.com/page?param=value";
// Parse the URL
$url_parts = parse_url($url);
// Manipulate the URL
$url_parts['path'] = '/newpage';
$url_parts['query'] = 'newparam=newvalue';
// Rebuild the URL
$new_url = http_build_url($url_parts);
echo $new_url;