繁体   English   中英

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

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

网址字串

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

我想从网址获取“计算机”。 前“计算机”,“手机”

尝试类似

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

正则表达式匹配从字符串开头( ^ )到最后一个/( \\/ )的所有内容( .* )。 然后,它再次匹配所有内容( .* ),但结尾处的.html除外,并期望字符串在该字符串( $ )之后结束。

第二个.*周围的方括号允许您将替换中匹配的那部分称为$1

您可以将URL转换为attay并使用array_pop()获取最后一个元素:

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

试试这个代码:

//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];

为了方便起见,这是另一个选择:

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

上面的示例假定应用程序至少在PHP 5.4上运行以使用数组取消引用。

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