How to remove URL Anchor (Fragment) using PHP?

The best option is using the parse_url() function:

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.

Natural de Salvador-BA, é graduado em Analise de Sistemas pela Universidade Católica do Salvador (UCSal, 2003), e Especialista em Engenharia de Software pela Universidade Salvador (2010).

Deixe uma resposta

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