Removing the hash part of an URL

A url may contain a hash/an anchor reference. If you need to remove it from url, it’s quite easy. Here’s a short recipe on how to do it in PHP (including a little test input):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$urls = array(
	'http://example.com/',
	'http://example.com/#test',
	'http://example.com/?id=1',
	'http://example.com/?id=1#test',
	'http://example.com/?id=1&id2=2#test#test',
	'http://example.com/?id=1#test#test'
);
 
foreach ($urls as $url) {
	if (strpos($url, '#')) {
		$url = substr($url, 0, strpos($url, '#'));
	}
	echo $url, "\n";
}

Apart from removing the hash ending from urls, the function can naturally also be used on any number of other similar cases, where you need to trim a string.