Getting the last part of an URL with PHP
Published on 2022-03-25 • Modified on 2022-03-25
This snippet shows how to get the last part of an URL with PHP. It's a kind of a relic of the past! Indeed, this basename()
function can typically return the "script" (file) that displays a page. This is no more true as websites' front controllers are generally hidden, and SEO URLs are generated. But, it's convenient because it's often helpful to get this last part like an ID, a UUID or even a slug, like in this example.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet195Trait
{
public function snippet195(): void
{
$snippetUrl = 'https://www.strangebuzz.com/en/snippets/getting-the-last-part-of-an-url-with-php';
echo 'URL: '.$snippetUrl.PHP_EOL;
echo 'basename: '.basename($snippetUrl);
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc More on the web Random snippet