Removing anchor (#hash) from URL

后端 未结 4 508
天命终不由人
天命终不由人 2021-01-02 09:11

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/

4条回答
  •  一向
    一向 (楼主)
    2021-01-02 09:34

    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();
    

提交回复
热议问题