缩短特定字符串的功能

I have this string:

$str="http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";

Is there a built-in php function that can shorten it by removing the ._SL110_.jpg part, so that the result will be:

http://ecx.images-amazon.com/images/I/418lsVTc0aL

I would recommend using:

$tmp = explode("._", $str);

and then using $tmp[0] for your purpose, if you make sure the part you want to get rid of is always separated by "._" (dot-underscore) symbols.

well, it depends if you need a regexp replace (if you don't know the complete value) or if you can do a simple str_replace like below:

$str = str_replace(".SL110.jpg", "", "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg");

No, it is not (at least not directly). Such URL shorteners usually generate unique ID and remember your original URL and generated ID. When you enter such url, you start a script, which looks for given ID and then redirect to target URL.

If you want just cut of some portion of your string, then assuming that filename format is as you shown, just look for 1st dot and substr() to that place. Or

$tmp = explode('.', $filename);
$shortName = $tmp[0];

If suffix ._SL110_.jpg is always there, then simply str_replace('._SL110_.jpg', '', $filename) could work.

EDIT

Above was example for filename only. Whole code would be:

$url = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
$urlTmp = explode('/', $url);
$fileNameTmp = explode( '.', $urlTmp[ count($urlTmp)-1 ] );

$urlTmp[ count($urlTmp)-1  ] = $fileNameTmp[0];
$newUrl = implode('/', $urlTmp );

printf("Old: %s
New: %s
", $url, $newUrl);

gives:

Old: http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg
New: http://ecx.images-amazon.com/images/I/418lsVTc0aL

You can use preg_replace().

For example preg_replace("/\.[^\.]+\.jpg$/i", "", $str);

no, there's not any built in URL shortener php function, if you want to do something similar you can use the substring or create a function that generates a short link and stores the long and short value somewhere in database and display only the short one.

you could do this substr($data,0,strpos($data,"._")), if what you want is to strip everything after "._"

You can try

$str = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
echo "<pre>";

A.

echo strrev(explode(".", strrev($str), 3)[2]) , PHP_EOL;

B.

echo pathinfo($str,PATHINFO_DIRNAME) . PATH_SEPARATOR . strstr(pathinfo($str,PATHINFO_FILENAME),".",true), PHP_EOL;

C.

echo preg_replace(sprintf("/.[^.]+\.%s$/i", pathinfo($str, PATHINFO_EXTENSION)), null, $str), PHP_EOL;

Output

http://ecx.images-amazon.com/images/I/418lsVTc0aL

See Demo