简体   繁体   English

如何在PHP中从字符串中获取特定单词

[英]how to get a specific word out of string in php

I am working on a wordpress plugin. 我正在开发一个wordpress插件。 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 . 我想获取我网站的网址,并从中获取页面名称,例如www.example.com/pagename在这种情况下,我需要pagename so for that I used native PHP function $_SERVER['REQUEST_URI'] to get URL of my website. 因此,我使用本地PHP函数$_SERVER['REQUEST_URI']来获取我网站的URL。 I stored it in $url variable as shown below. 我将其存储在$url变量中,如下所示。

$url= $_SERVER['REQUEST_URI'];

I get this when I echo url var 当我回应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 . 我如何从该字符串中获取wellington并将其存储在$name

Actually you should use a router, like https://github.com/auraphp/Aura.Router or any other. 实际上,您应该使用路由器,例如https://github.com/auraphp/Aura.Router或其他任何路由器。 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. 如果您想获得第二个uri段。

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. 尽管这取决于您是否可以确定传入的URL总是以相同的格式返回。 If $_SERVER['REQUEST_URI'] returned something like /ifar/something/wellington/ then the results of the above wouldn't be as you expected. 如果$_SERVER['REQUEST_URI']返回/ifar/something/wellington/则上述结果将不符合您的预期。

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. 潜在地,您可以考虑提取完整的URL,然后使用parse_url()提取完整的路径,然后确定所需的部分。

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. 尽管上面的方法可能就足够了,但是我不能肯定地说它们将适用于所有用例,因为我不知道您的程序的来龙去脉。

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

In $name you got the separate strings in array. 在$ name中,您获得了数组中的单独字符串。 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. 如果您的名字将在域名之后的网址中排在第一位,则可以通过执行上述回显来获取名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM