Reputation: 7
My string:
$string = '/my-picture-gallery-1000x2000.jpg';
I need to remove everything after the last occurrence of "-" (including "-") in the string and stop at the "." in the string.
So the output should read as:
/my-picture-gallery.jpg
but I need it to stop and keep everything after the "."
Upvotes: 0
Views: 210
Reputation: 3734
Try this :
$string = '/my-picture-gallery-1000x2000.jpg';
$ext= strstr($string, '.');
$dash=strrpos($string,'-');
$filename= substr($string, 0 ,$dash);
echo $filename.$ext;
In a short form , you can use :
$filename = substr($string, 0 ,strrpos($string,'-')).strstr($string, '.');
Upvotes: 0
Reputation: 6692
if(false !== $pos = strrpos($string, '-'))
$s = substr($string, 0, $pos);
First check if the needle is in the heystack using the reverse search. Then get the string from start up to the found position.
According to your edit a regular expression would be appropriate. This has also the advantage that it can handle UTF8 file pathes.
$new_name = preg_match('~^(.*)-[^-.]*(\..*)$~u', $string, $matches)
? $matches[1].$matches[2]
: $string
;
Upvotes: 0
Reputation: 2704
Should be able to use PHP's strstr in-built function in combination with str_replace to get the result you're after
$string = '/my-picture-gallery-1000x2000.jpg';
echo str_replace(strrchr($string, '-'), '', $string) . strstr($string, '.');
That would leave you with:
/my-picture-gallery.jpg
Slightly more readable version
$string = '/my-picture-gallery-1000x2000.jpg';
$dimensions = strrchr($string, '-');
$extension = strrchr($string, '.');
$image = str_replace($dimensions, '', $string) . $extension;
Upvotes: 3
Reputation: 262
$string = '/my-picture-gallery-1000x2000.jpg';
echo substr($string,0,strrpos($string,'-')) . substr($string,strrpos($string,'.'));
Upvotes: 2
Reputation: 1
you can use explode() function. It returns array of strings. Just choose part or parts of string and combine them in one string. More about explode() function at: http://php.net/manual/en/function.explode.php
Upvotes: 0