Php 获取特定字符后的字符串,同时避免UTF-8错误
我在发帖前做过研究,但找不到答案。如何获取字符串中某个字符后的部分 例如,对于字符串:Php 获取特定字符后的字符串,同时避免UTF-8错误,php,utf-8,Php,Utf 8,我在发帖前做过研究,但找不到答案。如何获取字符串中某个字符后的部分 例如,对于字符串: gallery/user/profile/img_904.jpg 我想返回: img_904.jpg 我还担心basename()关于包含亚洲字符的UTF-8文件名的bug。 <?php $path = 'gallery/user/profile/img_904.jpg'; $filename = substr(strrchr($path, "/"), 1); echo $filename;
gallery/user/profile/img_904.jpg
我想返回:
img_904.jpg
我还担心basename()
关于包含亚洲字符的UTF-8文件名的bug。
<?php
$path = 'gallery/user/profile/img_904.jpg';
$filename = substr(strrchr($path, "/"), 1);
echo $filename;
?>
这将帮助您..在这种情况下,您可以使用: 例如,作为一个更一般的示例,如果您想获取最后一个
|
之后的字符串部分,可以使用如下方法:
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);
}
从:
注意:
basename()具有区域设置意识,因此,要让它看到具有多字节字符路径的正确basename,必须使用setlocale()函数设置匹配的区域设置
哪个角色?到目前为止您尝试了什么?
gallery/user/profile/img_904.jpg
是路径。我想返回img_904.jpg
是否已修复basename()?处理亚洲字符?啊,不知道我们在处理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);
}
$path = gallery/user/profile/img_904.jpg;
$temp = explode('/', $path);
$filename = $temp[count($temp)-1];