2012-05-27 216 views
11

鉴于以下字符串如何使用PHP从字符串中删除子字符串?

http://thedude.com/05/simons-cat-and-frog-100x100.jpg 

我想用substrtrim(或任何你找到更合适)返回此

http://thedude.com/05/simons-cat-and-frog.jpg 

也就是说,除去-100x100。我需要的所有图像都会在扩展名之前立即标记为文件名的末尾。

似乎有对此回应红宝石和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

有什么建议?

+3

你打算硬编码子字符串的值吗?或者你想匹配任何-WIDTHxHEIGHT.ext形式的子字符串? –

+0

你介意链接到你找到的Ruby和Python版本吗?那里使用的技术可能是相关的。 – Ryan

+0

@minitech - 在OP – pepe

回答

24

如果你想匹配任何宽度/高度值:

$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
+4

谢谢JS - 我知道一个正则表达式即将到来! – pepe

+0

毕竟是说和做完了,这可能是多功能的解决方案,以防这些缩略图最终改变大小 – pepe

+0

+ +1为清晰的解释正则表达式 – rdjs

3

如果-100x100是您尝试从所有字符串中删除的唯一字符,为什么不使用str_replace

$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg"; 
str_replace("-100x100", "", $url); 
+1

中增加了几个链接完美thx!谁先回答? – pepe

14
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg"; 
$new_url = str_replace("-100x100","",$url); 
6
$url = str_replace("-100x100.jpg", '.jpg', $url); 

使用-100x100.jpg作为防弹解决方案。

+0

但他需要扩展名保留,所以添加'.jpg'作为重置价值 –

+0

MihaiStancu:刚刚编辑我的答案。谢谢。 – flowfree

相关问题