在避免UTF-8错误的同时获取特定字符后的字符串


Get String After a Certain Character While Avoiding UTF-8 Bugs

我在发布之前已经做了研究,但找不到答案。如何获取字符串中某个字符后面的部分?

例如,对于字符串:

gallery/user/profile/img_904.jpg

我想退货:

img_904.jpg

我还担心basename()关于包含亚洲字符的UTF-8文件名的错误。

在这种情况下,您可以只使用basename()函数:

php > $path = 'gallery/user/profile/img_904.jpg';
php > echo basename($path);
img_904.jpg

作为一个更一般的例子,例如,如果你想获得最后一个|之后的字符串部分,你可以使用这样的方法:

php > $string = 'Field 1|Field 2|Field 3';
php > echo substr(strrchr($string, '|'), 1);
Field 3

甚至:

php > $string = 'Field 1|Field 2|Field 3';
php > echo substr($string, strrpos($string, '|') + 1);
Field 3

编辑

您注意到basename()中UTF-8处理的问题,这也是我在几个版本的PHP中遇到的问题。我使用以下代码作为UTF-8路径的变通方法:

/**
 * Returns only the file component of a path. This is needed due to a bug
 * in basename()'s handling of UTF-8.
 *
 * @param string $path Full path to to file.
 * @return string Basename of file.
 */
function getBasename($path)
{
    $parts = explode('/', $path);
    return end($parts);
}

来自PHP basename()文档:

注意:basename()是区域设置感知的,因此要想看到具有多字节字符路径的正确basename,必须使用setlocale()函数设置匹配的区域设置。

<?php
$path = 'gallery/user/profile/img_904.jpg';
$filename = substr(strrchr($path, "/"), 1);
echo $filename; 

?>

这将对你有所帮助。。

$path = gallery/user/profile/img_904.jpg;
$temp = explode('/', $path);
$filename = $temp[count($temp)-1];