Removing Anchor (#hash) from URL

Is there any reliable way in PHP to clear URL anchor tags?

So the input:

http://site.com/some/#anchor

Outputs:

http://site.com/some/

+8
php
source share
4 answers

Using strstr ()

$url = strstr($url, '#', true); 

Using strtok ()

A shorter way using strtok :

 $url = strtok($url, "#"); 

Using explode ()

An alternative way to separate the URL from the hash:

 list ($url, $hash) = explode('#', $url, 2); 

If you don't want $hash , you can omit it in list :

 list ($url) = explode('#', $url); 

With PHP version> = 5.4 you don’t even need to use list :

 $url = explode('#', $url)[0]; 

Using preg_replace ()

Mandatory regular expression:

 $url = preg_replace('/#.*/', '', $url); 

Using Purl

Purl is a neat URL manipulation library:

 $url = \Purl\Url::parse($url)->set('fragment', '')->getUrl(); 
+17
source share

There is another option with parse_url () ;

 $str = 'http://site.com/some/#anchor'; $arr = parse_url($str); echo $arr['scheme'].'://'.$arr['host'].$arr['path']; 

Output:

 http://site.com/some/ 
+3
source share

Alternative way

 $url = 'http://site.com/some/#anchor'; echo str_replace('#'.parse_url($url,PHP_URL_FRAGMENT),'',$url); 
0
source share

Using parse_url ():

 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'] : ''); } 
0
source share

All Articles