PHP:截断字符串

时间:2018-06-26 10:28:04

标签: php

$urlPath = "http://localhost:8000/img/mercedes-benz-a-class-image.png";
$imgUrlPath = "http://localhost:8000/img/";


$imageName = ltrim($urlPath, $imgUrlPath);

我有ercedes-benz-a-class-image.png,而没有第一个m

$imageName = preg_replace($imgUrlPath, "", urlPath);

那是行不通的...

如何获得一行mercedes-benz-a-class-image.png

2 个答案:

答案 0 :(得分:0)

要从路径获取文件名,只需使用basename()

$urlPath = "http://localhost:8000/img/mercedes-benz-a-class-image.png";
$imageName = basename($urlPath);

Live Demo

要获取目录名称,请使用dirname

$urlPath = "http://localhost:8000/img/mercedes-benz-a-class-image.png";
echo $dirName = dirname($urlPath);

Live Demo

编辑来自您的评论

文件名中不能包含以下字符

enter image description here

答案 1 :(得分:0)

只需使用str_replace

$urlPath = "http://localhost:8000/img/mercedes-benz-a-class-image.png";
$imgUrlPath = "http://localhost:8000/img/";


$imageName = str_replace($imgUrlPath, "", $urlPath);

涉及正则表达式只会使事情变得如此简单。从文档中:

  

如果不需要花哨的替换规则(如正则表达式),则应始终使用此函数而不是preg_replace()