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?

3
  • 3
    Do you plan on hardcoding the value of the substring? Or do you want to match any -WIDTHxHEIGHT.ext form of substring? Commented May 27, 2012 at 2:38
  • Would you mind linking to the Ruby and Python versions you found? The techniques used there are probably relevant. Commented May 27, 2012 at 2:40
  • @minitech - added a few links in OP Commented May 27, 2012 at 2:47

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

after all is said and done, this may be the versatile solution, in case these thumbnails end up changing in size
23
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);

Comments

10
$url = str_replace("-100x100.jpg", '.jpg', $url);

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

1 Comment

But he needs the extension to remain, so add '.jpg' as the replacement value
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.