15

Given the following string

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

I would like to use substr or trim (or whatever you find more appropriate) to return this

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

that is, to remove the -100x100. All images I need will have that tagged to the end of the filename, immediately before the extension.

There appears to be responses for this on SO re Ruby and Python but not PHP/specific to my needs.

How to remove the left part of a string?

Remove n characters from a start of a string

Remove substring from the string

Any suggestions?

Community
  • 1
  • 1
pepe
  • 9,799
  • 25
  • 110
  • 188

4 Answers4

27

If you want to match any width/height values:

  $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 );

Demo: http://codepad.org/cnKum1kd

The pattern used is pretty basic:

/     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
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • after all is said and done, this may be the versatile solution, in case these thumbnails end up changing in size – pepe May 27 '12 at 02:48
23
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);
WojtekT
  • 4,735
  • 25
  • 37
9
$url = str_replace("-100x100.jpg", '.jpg', $url);

Use -100x100.jpg for bullet-proof solution.

flowfree
  • 16,356
  • 12
  • 52
  • 76
3

If -100x100 are the only characters you're trying to remove from all of your strings, why not use str_replace?

$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
str_replace("-100x100", "", $url);
Norse
  • 5,674
  • 16
  • 50
  • 86