开发者

How to get just last word for a variable in a PHP "$_SERVER['REQUEST_URI']" request?

开发者 https://www.devze.com 2023-01-07 01:56 出处:网络
I\'m using WAMP and the root folder of my page is: http://localhost/projects/bp/ In a Worpress application and I want to give unique id\'s to the body tag of every Page. So I did the following:

I'm using WAMP and the root folder of my page is: http://localhost/projects/bp/

In a Worpress application and I want to give unique id's to the body tag of every Page. So I did the following:

<?php
    开发者_JAVA百科$page = $_SERVER['REQUEST_URI'];
    $page = str_replace("/","",$page);
    $page = str_replace(".php","",$page);
    $page = str_replace("?s=","",$page);
    $page = $page ? $page : 'default'
?>

<body id="<?php echo $page ?>">

When I clicked the Aboutpage the URL change to the following: http://localhost/projects/bp/about and $page showed the following value:projectsbpabout

What can I do so that $page just show the last word of the URL. In this case, about, I don't want the projectsbp part)?

Do I have to change something in the Wordpress routing?


I would use PHP's built-in path parsing functions to do this.

Use parse_url() to cut off the query and get only the path part:

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

(parse_url is used to parse full URLs but should work fine for this. The second parameter is available since PHP 5.1.2.)

Then use basename() to extract the file name:

$pagename = basename($path, ".php");  // Will remove `.php` suffix

Additional thougths

Depending on how your site is structured, this method will not necessarily make for unique IDs. What if about is a sub-page in /bp and /bc? (If that is possible in Wordpress.) You would have two different pages with the same ID. In that case, you may want to use the full path as an identifier, converting slashes into underlines:

<body id="projects_bp_about">

also from own experience, I recommend using classes for this to avoid ID collisions if a page is named like an already existing elements on the page!

<body class="projects_bp_about">


As / is your separator, first create an array of all the loose parts: $parts = explode('/', $_SERVER['REQUEST_URI']); Now you just want the last element: $last_part = end($parts); of course this can also be done in one go:

$last_part = end(explode('/', $_SERVER['REQUEST_URI']));


to get only the last bit you can use

$page = array_pop(explode('/', $_SERVER['REQUEST_URI']));

explode the string by '/' and get the last piece.


instead of using str_replace you can use..

$pageArr = explode("/",$page);

it will give you array with three values you can capture the last one as about

0

精彩评论

暂无评论...
验证码 换一张
取 消