我需要获取/和/之间的 url 的最后一个字符串内容
例如:
http://mydomain.com/get_this/
or
http://mydomain.com/lists/get_this/
我需要获取get_this在网址中的位置。
trim() 删除尾部斜杠,strrpos() 查找最后一次出现的 /
(在修剪后),substr() 获取最后一次出现/
后的所有内容。
$url = trim($url, '/');
echo substr($url, strrpos($url, '/')+1);
查看输出
更好的是,你可以使用 basename(),就像 hakre 建议的那样:
echo basename($url);
查看输出
假设总是有一个尾部斜杠:
$parts = explode('/', $url);
$get_this = $parts[count($parts)-2]; // -2 since there will be an empty array element due to the trailing slash
如果没有:
$url = trim($url, '/'); // If there is a trailing slash in this URL instance get rid of it so we're always sure the last part is where we expect it
$parts = explode('/', $url);
$get_this = $parts[count($parts)-1];
这样的事情应该有效。
<?php
$subject = "http://mydomain.com/lists/get_this/";
$pattern = '/'/([^'/]*)'/$/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
只需使用 parse_url()
和 explode()
:
<?php
$url = "http://mydomain.com/lists/get_this/";
$path = parse_url($url, PHP_URL_PATH);
$path_array = array_filter(explode('/', $path));
$last_path = $path_array[count($path_array) - 1];
echo $last_path;
?>
你可以试试这个:
preg_match("/http:'/'/([a-z0-9'.]+)'/(.+)'/(.*)'/?/", $url, $matches);
print_r($matches);