How to remove URL Anchor (Fragment) using PHP?

To remove the URL anchor, or fragment, from a URL using PHP, you can use the parse_url() function. This function breaks down a URL into its individual components, such as the scheme (e.g. “http”), hostname, port, path, query string, and fragment.

To use the parse_url() function to remove the fragment, you can pass the URL as a string to the function and then access the fragment component using the ‘fragment’ key. For example:

function removeURLFragment($pstr_urlAddress = '') {
$larr_urlAddress = parse_url ( $pstr_urlAddress );
return $larr_urlAddress['scheme'].'://'.(isset($larr_urlAddress['user']) ? $larr_urlAddress['user'].':'.''.$larr_urlAddress['pass'].'@' : '').$larr_urlAddress['host'].(isset($larr_urlAddress['port']) ? ':'.$larr_urlAddress['port'] : '').$larr_urlAddress['path'].(isset($larr_urlAddress['query']) ? '?'.$larr_urlAddress['query'] : '');

$url = "";
$parsed_url = parse_url($url);
$clean_url = http_build_url($parsed_url);
echo $clean_url; // ""

Alternatively, you can use the function provided in the original example, which uses parse_url() to break down the URL into its individual components and then rebuilds the URL without the fragment component. This can be useful if you want to preserve other components of the URL, such as the query string, while removing the fragment.

It is generally recommended to use dedicated methods like parse_url() or http_build_url() to manipulate URLs, rather than using regular expressions or string manipulation, as these can be more reliable and less prone to errors.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Rolar para cima