How to remove a substring from a string using PHP?

php, string

Solution

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

Problem

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?

Original source

Related problems