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?
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.
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.
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.
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.
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
$url = "http://thedude.com/05/simons-cat-and-frog-100x100.jpg";
$new_url = str_replace("-100x100","",$url);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With