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/
$url = strstr($url, '#', true);
Shorter way, using strtok
:
$url = strtok($url, "#");
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];
Obligatory regex solution:
$url = preg_replace('/#.*/', '', $url);
Purl is neat URL manipulation library:
$url = \Purl\Url::parse($url)->set('fragment', '')->getUrl();
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With