1

我需要在/和/之间获取url的最后一个字符串内容

例如:

http://mydomain.com/get_this/

or

http://mydomain.com/lists/get_this/

我需要得到 get_this 在 url 中的位置。

4

5 回答 5

11

trim()删除尾部斜杠,strrpos()找到最后一次出现的/(在修剪之后),substr()获得最后一次出现/.

$url = trim($url, '/');
echo substr($url, strrpos($url, '/')+1);

查看输出


更好的是,您可以使用basename(),就像 hakre 建议的那样:

echo basename($url);

查看输出

于 2012-06-17T22:33:33.227 回答
1

假设总是有一个斜杠:

$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];
于 2012-06-17T22:33:22.937 回答
1

像这样的东西应该工作。

<?php
$subject = "http://mydomain.com/lists/get_this/";
$pattern = '/\/([^\/]*)\/$/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
于 2012-06-17T22:35:18.367 回答
1

只需使用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;

?>
于 2012-06-17T22:48:47.803 回答
0

你可以试试这个:

preg_match("/http:\/\/([a-z0-9\.]+)\/(.+)\/(.*)\/?/", $url, $matches);
print_r($matches);
于 2012-06-17T22:33:31.517 回答