Search code examples
phpurlstrip

PHP: How to strip all types of extensions from URL (incl. period)


I am new to PHP and hope someone can help me with this.

I want PHP to give me the name of the current page of my website. The important thing is that I need this without any leading slashes and without any trailing extensions etc., just the plain page name.

Example:
The URL of a page is http://www.myurl.com/index.php?lang=en In this case it should only return "index".

I found a way to get rid of the leading part using the following but have trouble to remove the trailing part since this is variable (it can be just .php or .php?lang=en or .php=lang=de etc.).

$pageName = basename($_SERVER["REQUEST_URI"]);

The only thing I found is the following but this doesn't cover the variable extension part:

$pageName = basename($_SERVER["REQUEST_URI"], ".php");

Can someone tell me how to get rid of the trailing part as well ?

Many thanks in advance, Mike


Solution

  • You can use parse_url in combination with pathinfo:

    <?php
    $input  = 'http://www.myurl.com/index.php?lang=en';
    $output = pathinfo(parse_url($input, PHP_URL_PATH), PATHINFO_FILENAME); 
    
    var_dump($output); // => index
    

    demo: https://eval.in/382330