Ammar Ul Hassan
Ammar Ul Hassan

Reputation: 906

how to get a specific word out of string in php

I am working on a wordpress plugin. I want to get the url of my website and get the page name out of that like www.example.com/pagename in this case I want pagename. so for that I used native PHP function $_SERVER['REQUEST_URI'] to get URL of my website. I stored it in $url variable as shown below.

$url= $_SERVER['REQUEST_URI'];

I get this when I echo url var

/ifar/wellington/

$name= "wellington"; /* I want it like this */ 

How can I get wellington out from this string and store it in $name.

Upvotes: 0

Views: 263

Answers (3)

pratik
pratik

Reputation: 49

$url= $_SERVER['REQUEST_URI'];
$name = explode("/",$url);
echo $name[1];

In $name you got the separate strings in array. You can get the name by doing echo like above if your name is going to come first in your url after your domain name.

Upvotes: 1

Mikey
Mikey

Reputation: 2704

There's a few methods you could use, I've put two quick and easy ones below:

// Method One
$url      = '/ifar/wellington/';
$url      = trim($url, '/');
$urlParts = explode('/', $url);
$name     = $urlParts[1];

// Method Two
$url  = '/ifar/wellington/';
$url  = trim($url, '/');
$name = substr($url, (strpos($url, '/') + 1));

Although it depends whether you can be certain that the URL you pass in is always going to return in the same format. If $_SERVER['REQUEST_URI'] returned something like /ifar/something/wellington/ then the results of the above wouldn't be as you expected.

Potentially you could look into pulling out the full URL and then using parse_url() to pull out the full path, and then working out what section you need.

Although the above methods may suffice, but I can't say for certain they will work for all use cases because I don't know the ins/outs of your program.

Upvotes: 1

ksimka
ksimka

Reputation: 1455

Actually you should use a router, like https://github.com/auraphp/Aura.Router or any other. But simple and quick answer for you will be

$parts = explode('/', trim($url, '/'));
$name = $parts[1];

if you want to get the 2nd uri segment.

Upvotes: 2

Related Questions