Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing anchor (#hash) from URL

Tags:

php

Is there any reliable way in PHP to clean a URL of anchor tags?

So input:

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

Outputs:

http://site.com/some/

like image 446
DomingoSL Avatar asked May 27 '13 12:05

DomingoSL


2 Answers

Using strstr()

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

Using strtok()

Shorter way, using strtok:

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

Using explode()

Alternative way to separate the url from the hash:

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

If you don't want the $hash at all, 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()

Obligatory regex solution:

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

Using Purl

Purl is neat URL manipulation library:

$url = \Purl\Url::parse($url)->set('fragment', '')->getUrl();
like image 107
Arnaud Le Blanc Avatar answered Sep 22 '22 12:09

Arnaud Le Blanc


There is also one other 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/
like image 34
Robert Avatar answered Sep 21 '22 12:09

Robert