gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:41:41 25 4
gpt4 key购买 nike

我在发帖前做了研究,但找不到答案。如何获取特定字符之后的字符串部分?

例如,对于字符串:

gallery/user/profile/img_904.jpg

我要返回:

img_904.jpg

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

最佳答案

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

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() documentation :

Note: basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

关于php - 在避免 UTF-8 错误的同时获取特定字符后的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34506761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com