开发者

Explode a string that contains the route to a file to changes the filename and reconstruct the route

开发者 https://www.devze.com 2023-02-28 10:21 出处:网络
I\'ve a backend that the user selects the route of the file, and I\'ve an input like: /images/soccer/2010-2011/last_match/image_example.jpg

I've a backend that the user selects the route of the file, and I've an input like:

/images/soccer/2010-2011/last_match/image_example.jpg

Then, with my PHP application I need to change that "image_example" because I encode the name for prevent problems. I split the file name with the last "." to seperate name from extension and then I return the new image name and extension... but I don't know how to identify the route, separate the name, and then rewrite the route.

So the worflow will be like:

  1. User inputs the route.
  2. The application identifies the image name.
  3. I call a function than 开发者_运维技巧changes the name.
  4. Reconstruct the rotue for the final copy/move.

Can anyone help me?

Thank you in advance!


You can use PHP's pathinfo function to split a file path into it's components. Like this:

$path_parts = pathinfo('/images/soccer/2010-2011/last_match/image_example.jpg');

The resulting array looks like this:

Array
(
    [dirname] => /images/soccer/2010-2011/last_match
    [basename] => image_example.jpg
    [extension] => jpg
    [filename] => image_example
)

With these informations you can then put together your new path:

$new_path = $path_parts['dirname'] . '/CHANGEDNAME_SAMEROUTE.' .
        $path_parts['extension'];


I think this is what you want to accomplish?

$sImageLocation = "/images/soccer/2010-2011/last_match/image_example.jpg";
$sPath = substr($sImageLocation, 0, strrpos($sImageLocation, "/")+1);
$sNewImageLocation = $sPath."image_new.jpg";

echo $sNewImageLocation; 
// will output: /images/soccer/2010-2011/last_match/image_new.jpg


Try something along the line of this:

$route = '/images/soccer/2010-2011/last_match/image_example.jpg';
preg_match('/^(.*?\/)([^.\/]*)(\.[a-z]*)$/', $route, $matches);
$route[1] = your_function($route[1]);
$route = implode($matches);

First it takes apart your route with a regular expression, applies your function to the filename part of the route and then reassembles it.

(The regular expression might not be the best option, but I think it does the job.)


If you just want to change the last part of the route/url, then this might be the laziest option:

$route = preg_replace("#(?<=/)\w+\.(jpe?g|png|gif|webp)$#",
                      "NEWNAME.$1", $route);

If the filename can contain other symbols than letters/numbers/underscores, then use [^/]+ instead of \w+. Also adapt the list of acceptable extensions if you must.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号