How to remove URL Anchor (Fragment) using PHP?

The best option is using the parse_url() function:

[code language=”php”]
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’] : ”);

I think this is way better, since the knowledge of the structure of the URL is encapsulated. Chances are pretty large than using regexes or string manipulation, one will forget some scenario’s whereas dedicated methods are more reliable.

Deixe uma resposta

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