-3

My string looks like this:

$str = www.example.com/forums/pages/name.php

I will like to get this:

name

I have tried:

echo rtrim($str,".php");

But I am getting www.example.com/forums/pages/name

Thanks a lot.

jww
  • 97,681
  • 90
  • 411
  • 885
d0uph1x
  • 39
  • 1
  • 7
  • 1
    "I will like to remove the last character from a string, clear the characters before it and return the rest." -> you'll get an empty string :) Can you rephrase that please, and share your attempts? – Jeto Dec 23 '18 at 17:47
  • 2
    Possible duplicate of [Break up/parse a URL into its constituent parts in php](https://stackoverflow.com/q/46796837/608639) – jww Dec 23 '18 at 20:39

2 Answers2

5

You can achieve what you want by using pathinfo()

$a_info = pathinfo("www.site.com/forums/pages/name.php");
echo $a_info["filename"];

$a_info["filename"] will give you "name"

you can also get other details from pathinfo

Array
(
    [dirname] => www.site.com/forums/pages
    [basename] => name.php
    [extension] => php
    [filename] => name
)
Jon Moore
  • 66
  • 2
-1

The substr() function returns a part of a string.

Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

link

echo substr($str,26,29); // this will give output -  name.php

EDIT:

$str = "www.example.com/forums/pages/name.php";
$start = strrpos($str,"/")+1; // using strrpos to get position of "/"
$length = strrpos($str,".")-$start; // using strrpos to get position of "." and then subtracting start position to get its length
echo substr($str,$start,$length); // this will echo out the name
Sitepose
  • 304
  • 1
  • 13