PHP – Get the Anchor Part of the URL by parse_url()

The parse_url() function dissect the URL completely. Try the following PHP code.

<?php
  $url = 'http://username:password@hostname/path?arg=value#anchor';

  // Print all components of the parsed url
  print_r(parse_url($url));

  // Get the anchor part
  echo parse_url($url, PHP_URL_FRAGMENT);
?>


 

You will get an array as follow.

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

 

And the echo parse_url($url, PHP_URL_FRAGMENT) will return “anchor”. For more information, please refer to the PHP doc.
PHP: parse_url – Manual

The following post make use of both client side and sever side programming to store the anchor in cookie and i think it is quite inspiring. Take a look if you are interested.
stoimen’s web log – Read The Anchor Part of The URL … with PHP

Done =)

2 thoughts on “PHP – Get the Anchor Part of the URL by parse_url()”

  1. U used a string as the URi. how to get the URI dynamically ?
    $_SERVER[‘REQUEST_URI’] does not include the # part.

    Like

Leave a reply to Istiaque Ahmed Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.