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

87 views Asked by At

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

6

There are 6 answers

0
Yoshi On BEST ANSWER

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

2
Mox On

A tutorial on how to do it

With an .htaccess file you can:

Redirect the user to different page

Password protect a specific directory

Block users by IP Preventing hot

linking of your images

Rewrite URIs

Specify your own Error Documents

0
codeneuss On

One possible way is:

$url = "http://www.myurl.com/index.php?lang=en";

preg_match('/\/([\w-_]+)\.php/i',$url,$match);
echo $match[1];

If you need help with the regex look here: https://regex101.com/r/cM8sS3/1

3
kevin On

here is simplest solution.

$pagename = basename($_SERVER['PHP_SELF']);
$a = explode(".",$pagename);
echo $a[0];

0
Bruce On

Try this

//return url
$pageName = base64_decode($_GET["return_url"]);

function Url($pageName) {
    $pageName= strtolower($pageName);
    $pageName= str_replace('.',' ',$pageName);
    $pageName= preg_replace("/[^a-z0-9_\s-]/", "", $pageName);
    $pageName= preg_replace("/[\s-]+/", " ", $pageName);
    $pageName= preg_replace("/[\s_]/", "-", $pageName);
    return $pageName ;
}
$cleanurl=Url($pageName);
echo $cleanurl;
0
Ben T On

This is a situation where I would just use a regular expression. Here's the code:

$pagename = basename("http://www.myurl.com/index.php?lang=en");

$pagename = preg_replace("/\..*/", "", $pagename);

You can see a working demo here: https://ideone.com/RdrHzc

The first argument is an expression that matches for a literal period followed by any number of characters. The second argument tells the function to replace the matched string with an empty string, and the last argument is the variable to operate on.