简体   繁体   English

获取 URL PHP 的最后一部分

[英]Get Last Part of URL PHP

I'm just wondering how I can extract the last part of a URL using PHP.我只是想知道如何使用 PHP 提取 URL 的最后一部分。

The example URL is:示例网址是:

http://domain.example/artist/song/music-videos/song-title/9393903

Now how can I extract the final part using PHP?现在如何使用 PHP 提取最终部分?

9393903

There is always the same number of variables in the URL, and the id is always at the end. URL 中始终存在相同数量的变量,并且 id 始终位于末尾。

The absolute simplest way to accomplish this, is with basename()最简单的方法是使用basename()

echo basename('http://domain.example/artist/song/music-videos/song-title/9393903');

Which will print哪个会打印

9393903 9393903

Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.当然,如果末尾有查询字符串,它将包含在返回值中,在这种情况下接受的答案是更好的解决方案。

Split it apart and get the last element:将其拆分并获取最后一个元素:

$end = end(explode('/', $url));
# or:
$end = array_slice(explode('/', $url), -1)[0];

Edit: To support apache-style-canonical URLs, rtrim is handy:编辑:为了支持 apache-style-canonical URLs, rtrim很方便:

$end = end(explode('/', rtrim($url, '/')));
# or:
$end = array_slice(explode('/', rtrim($url, '/')), -1)[0];

A different example which might me considered more readable is ( Demo ):另一个我认为更具可读性的示例是( Demo ):

$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);

This example also takes into account to only work on the path of the URL.此示例还考虑到仅对 URL 的路径起作用。


Yet another edit (years after), canonicalization and easy UTF-8 alternative use included (via PCRE regular expression in PHP):另一个编辑(多年后),规范化和简单的 UTF-8 替代使用包括(通过 PHP 中的 PCRE 正则表达式):

<?php

use function call_user_func as f;
use UnexpectedValueException as e;

$url = 'http://example.com/artist/song/music-videos/song-title/9393903';

$result = preg_match('(([^/]*)/*$)', $url, $m)

    ? $m[1]
    : f(function() use ($url) {throw new e("pattern on '$url'");})
    ;

var_dump($result); # string(7) "9393903"

Which is pretty rough but shows how to wrap this this within a preg_match call for finer-grained control via PCRE regular expression pattern.这很粗略,但展示了如何将它包装在preg_match调用中,以通过 PCRE 正则表达式模式进行更细粒度的控制。 To add some sense to this bare-metal example, it should be wrapped inside a function of its' own (which would also make the aliasing superfluous).为了给这个裸机示例增加一些意义,它应该被包装在它自己的函数中(这也会使别名变得多余)。 Just presented this way for brevity.为简洁起见,仅以这种方式呈现。

You can use preg_match to match the part of the URL that you want.您可以使用preg_match来匹配您想要的 URL 部分。

In this case, since the pattern is easy, we're looking for a forward slash ( \/ and we have to escape it since the forward slash denotes the beginning and end of the regular expression pattern), along with one or more digits ( \d+ ) at the very end of the string ( $ ).在这种情况下,由于模式很简单,我们正在寻找一个正斜杠( \/并且我们必须转义它,因为正斜杠表示正则表达式模式的开始和结束),以及一个或多个数字( \d+ )在字符串的最后( $ )。 The parentheses around the \d+ are used for capturing the piece that we want: namely the end. \d+周围的括号用于捕获我们想要的部分:即结尾。 We then assign the ending that we want ( $end ) to $matches[1] (not $matches[0] , since that is the same as $url (ie the entire string)).然后我们将我们想要的结尾( $end )分配给$matches[1] (不是$matches[0] ,因为它与$url相同(即整个字符串))。

$url='http://domain.example/artist/song/music-videos/song-title/9393903';

if(preg_match("/\/(\d+)$/",$url,$matches))
{
  $end=$matches[1];
}
else
{
  //Your URL didn't match.  This may or may not be a bad thing.
}

Note: You may or may not want to add some more sophistication to this regular expression.注意:您可能希望也可能不希望向此正则表达式添加一些更复杂的功能。 For example, if you know that your URL strings will always start with http:// then the regex can become /^http:\/\/.*\/(\d+)$/ (where .* means zero or more characters (that aren't the newline character)).例如,如果您知道您的 URL 字符串将始终http://开头,那么正则表达式可以变为/^http:\/\/.*\/(\d+)$/ (其中.*表示零个或多个字符(不是换行符))。

If you are looking for a robust version that can deal with any form of URLs , this should do nicely:如果您正在寻找可以处理任何形式的URL的强大版本,这应该很好:

<?php

$url = "http://foobar.example/foo/bar/1?baz=qux#fragment/foo";
$lastSegment = basename(parse_url($url, PHP_URL_PATH));
$id = strrchr($url,"/");
$id = substr($id,1,strlen($id));

Here is the description of the strrchr function: http://www.php.net/manual/en/function.strrchr.php这里是strrchr函数的描述: http ://www.php.net/manual/en/function.strrchr.php

Another option:另外的选择:

$urlarray=explode("/",$url);
$end=$urlarray[count($urlarray)-1];

One of the most elegant solutions was here Get characters after last / in url最优雅的解决方案之一是在这里Get characters after last / in url

by DisgruntledGoat由不满的山羊

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

strrpos gets the position of the last occurrence of the slash; strrpos 获取最后一次出现斜线的位置; substr returns everything after that position. substr 返回该位置之后的所有内容。

One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));一个班轮: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));

Get URI, trim slashes, convert to array, grab last part获取 URI,修剪斜线,转换为数组,抓取最后一部分

A fail safe solution would be:故障安全解决方案是:

Referenced from https://stackoverflow.com/a/2273328/2062851引用自https://stackoverflow.com/a/2273328/2062851

function getLastPathSegment($url) {
    $path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
    $pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
    $pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash

    if (substr($path, -1) !== '/') {
        array_pop($pathTokens);
    }
    return end($pathTokens); // get the last segment
}

echo getLastPathSegment($_SERVER['REQUEST_URI']); //9393903

this will do the job easily to get the last part of the required URL这将轻松完成工作以获取所需 URL 的最后一部分

$url="http://domain.example/artist/song/music-videos/song-title/9393903";
$requred_string= substr(strrchr($url, "/"), 1);

this will get you the string after first "/" from the right.这将在右边的第一个“/”之后为您提供字符串。

$mylink = $_SERVER['PHP_SELF'];
$link_array = explode('/',$mylink);
echo $lastpart = end($link_array);
function getLastPathSegment($url) {
    $arr = explode('/', $url);
    return $arr[count($arr) - 1];
}

1-liner 1班

$end = preg_replace( '%^(.+)/%', '', $url );

// if( ! $end ) no match.

This simply removes everything before the last slash, including it.这只是删除最后一个斜杠之前的所有内容,包括它。

One line working answer:一线工作答案:

$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));

Output: drink输出:饮料

I'm happy that you asked this question!我很高兴你问这个问题!

You can use this code:-您可以使用此代码:-

$request_uri = $_SERVER['REQUEST_URI'];
$request_uri_arr = explode('/', $request_uri);

$node_url = end($request_uri_arr);
echo $node_url;//this will print the last part of the url;

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

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