Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a substring from a string using PHP?

Tags:

string

php

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?

like image 316
pepe Avatar asked May 27 '12 02:05

pepe


People also ask

How can I remove part of a string in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How do I trim a string after a specific character in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do you remove portion of a string before a certain character in PHP?

You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.

How do I remove a substring?

To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.


2 Answers

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
like image 118
Sampson Avatar answered Oct 10 '22 14:10

Sampson


$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);
like image 29
WojtekT Avatar answered Oct 10 '22 14:10

WojtekT