Core\Uri::fragment
$uri->fragment(): ?stringReturns the fragment of an address. The fragment is the text after the #, such as install in https://example.com/guide#install. A browser uses it to scroll to one part of a page, and does not send it to the server.
$uri->fragment() returns the text without the #, as it was written. Escapes such as %20 stay in it. Use Core\Uri::decodeComponent to read its text.
The result is null when the address has no #. The result is "" when nothing is written after the #, as in https://example.com/guide#.
The examples below read a fragment, show the null and "" results, and remove the fragment before a program saves a link.
Return value
Returns ?string. The fragment, without the #. The result is null when the address has no #. It is "" when nothing is written after the #.
Examples
The section of a page
<?nvs// Shows how to read the fragment of an address.
var $link = Core\Uri::parse('https://example.com/guide?lang=en#install');
// The fragment is the text after the `#`. This prints install.echo $link->fragment(), "\n";
// Escapes stay in the fragment. This prints getting%20started.echo Core\Uri::parse('https://example.com/guide#getting%20started')->fragment(), "\n";installgetting%20startedNo fragment and an empty one
<?nvs// Shows the difference between no fragment and an empty fragment.
// The address has no `#`. The result is `null`, so this prints none.echo Core\Uri::parse('https://example.com/guide')->fragment() ?? 'none', "\n";
// Nothing is written after the `#`. The result is "", so this prints "".echo "\"", Core\Uri::parse('https://example.com/guide#')->fragment() ?? 'none', "\"\n";none""Remove the fragment before saving a link
<?nvs// Shows how a program removes the fragment, so that two links to one page are saved once.
// In a real program, these links come from the pages a crawler reads.array<string> $links = [ 'https://example.com/guide#install', 'https://example.com/guide#usage', 'https://example.com/faq',];
array<string> $saved = [];foreach ($links as string $link) { var $uri = Core\Uri::parse($link); if ($uri->fragment() != null) { // `with` builds a new address. A `null` fragment removes the `#` and the text after it. $uri = $uri->with({ fragment: null }); } if (!Core\Arr::contains($saved, $uri->toString())) { $saved[] = $uri->toString(); }}
// This prints https://example.com/guide and https://example.com/faq.foreach ($saved as string $page) { echo $page, "\n";}https://example.com/guidehttps://example.com/faq