简体   繁体   中英

PHP Remove Everything After Character and Stop Before Character

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 "."

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;
$string = '/my-picture-gallery-1000x2000.jpg';
echo substr($string,0,strrpos($string,'-')) . substr($string,strrpos($string,'.'));

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

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, '.');
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
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM