php - 文本末尾的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3149987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:52:18  来源:igfitidea点击:

php - substring from end of text

php

提问by Dori

I am looking to get the substring from the end of a line of text, say

我希望从一行文本的末尾获取子字符串,例如

$text = "bob/hello/myfile.zip";

I want to be able to obtain the file name, which i guess would involve getting everything after the last slash as a substring, can anyone help me how to do this is PHP? A simple function like

我希望能够获得文件名,我想这将涉及将最后一个斜杠之后的所有内容作为子字符串,有人可以帮助我如何做到这一点是 PHP?一个简单的函数,如

$fileName = getFileName($text);

回答by Daniel Egeberg

Check out basename().

退房basename()

回答by bschaeffer

$text = "bob/hello/myfile.zip";
$file_name = end(explode("/", $text));
echo $file_name; // myfile.zip

end()returns the last element of a given array.

end()返回给定数组的最后一个元素。

回答by simplfuzz

For more general needs, use negative value for start parameter.
For e.g.

对于更一般的需求,请对 start 参数使用负值。
例如

<?php
$str = '001234567890';
echo substr($str,-10,4);
?>

will output
1234

将输出
1234

Using a negative parameter means that it starts from the start'th character from the end.

使用负参数意味着它从结尾的第 start'th 个字符开始。

回答by Scott Saunders

As Daniel posted, for this application you want to use basename(). For more general needs, strrchr()does exactly what the title of this post asks.

正如 Daniel 发布的那样,对于这个应用程序,您希望使用 basename()。对于更一般的需求,strrchr()正是这篇文章的标题所要求的。

http://us4.php.net/strrchr

http://us4.php.net/strrchr

回答by Curtis

I suppose you could use strrpos to find the last '/', then just get that substring:

我想你可以使用 strrpos 来找到最后一个 '/',然后只得到那个子字符串:

$fileName = substr( $text, strrpos( $text, '/' )+1 );

$fileName = substr( $text, strrpos( $text, '/' )+1 );

Though you'd probably actually want to check to make sure that there's a "/" in there at all, first.

尽管您可能实际上想先检查以确保那里有一个“/”。

回答by MakoBuk

function getSubstringFromEnd(string $string, int $length)
{
    return substr($string, strlen($string) - $length, $length);
}

function removeSubstringFromEnd(string $string, int $length)
{
    return substr($string, 0, strlen($string) - $length);
}

echo getSubstringFromEnd("My long text", 4); // text
echo removeSubstringFromEnd("My long text", 4); // My long