给出以下字符串
http://thedude.com/05/simons-cat-and-frog-100x100.jpg
我想使用substr
或trim
(或您认为更合适的任何内容)返回此
http://thedude.com/05/simons-cat-and-frog.jpg
即删除-100x100
。我需要的所有图像都会在扩展名之前标记到文件名的末尾。
似乎在SO和Ruby和Python上有这样的响应,但不是PHP /特定于我的需求。
How to remove the left part of a string?
Remove n characters from a start of a string
Remove substring from the string
有什么建议吗?
答案 0 :(得分:25)
如果您想匹配任何宽度/高度值:
$path = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
// http://thedude.com/05/simons-cat-and-frog.jpg
echo preg_replace( "/-\d+x\d+/", "", $path );
演示:http://codepad.org/cnKum1kd
使用的模式非常基本:
/ Denotes the start of the pattern - Literal - character \d+ A digit, 1 or more times x Literal x character \d+ A digit, 1 or more times / Denotes the end of the pattern
答案 1 :(得分:16)
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);
答案 2 :(得分:9)
$url = str_replace("-100x100.jpg", '.jpg', $url);
使用-100x100.jpg
进行防弹解决方案。
答案 3 :(得分:3)
如果-100x100
是您尝试从所有字符串中删除的唯一字符,为什么不使用str_replace
?
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
str_replace("-100x100", "", $url);