简体   繁体   English

如何从php中的URL获取单词?

[英]how to fetch word from url in php?

url string 网址字串

http://localhost/magento_prac/index.php/electronics/computers.html
http://localhost/magento_prac/index.php/electronics/cell-phones.html

I want to fetch 'computers' from url. 我想从网址获取“计算机”。 ex 'computers', 'cell-phones' 前“计算机”,“手机”

Try something like 尝试类似

$category = preg_replace('/^.*\/(.*)\.html$/', '$1', $url);

The regular expression matches everything ( .* ) from the start ( ^ ) of the string up until the last / ( \\/ ). 正则表达式匹配从字符串开头( ^ )到最后一个/( \\/ )的所有内容( .* )。 Then, it matches everything ( .* ) again except for the .html at the end and expects the string to end after that ( $ ). 然后,它再次匹配所有内容( .* ),但结尾处的.html除外,并期望字符串在该字符串( $ )之后结束。

The brackets around the second .* allow you to reference that part of the match in the substitution as $1 . 第二个.*周围的方括号允许您将替换中匹配的那部分称为$1

You can convert URL into attay and fetch last element with array_pop(): 您可以将URL转换为attay并使用array_pop()获取最后一个元素:

$urlArray = explode('/', $url);
$word = substr(array_pop($urlArray),0,-5);

try this code: 试试这个代码:

//get the url
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

//seperate the segments using explode()
$segments = explode('/', $url);

//and get the last segment
$last = explode('.', end($segments));

//use the last segment
echo $last[0];

For convenience, here's another option: 为了方便起见,这是另一个选择:

$url = 'http://localhost/magento_prac/index.php/electronics/computers.html';
$category = pathinfo($url)['filename']; // "computers"

Above example assumes the application is running at least on PHP 5.4 to use array de-referencing. 上面的示例假定应用程序至少在PHP 5.4上运行以使用数组取消引用。

pathinfo - Returns information about a file path. pathinfo返回有关文件路径的信息。

'dirname' => string 'http://localhost/magento_prac/index.php/electronics'
'basename' => string 'computers.html'
'extension' => string 'html'
'filename' => string 'computers'

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

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