find the filename from a string with php

纵然是瞬间 提交于 2019-12-19 18:39:05

问题


public/images/portfolio/i-vis/1.jpg

How could i remove all the path regardless of what the filename is using php?


回答1:


Have a look at basename()

$path = 'public/images/portfolio/i-vis/1.jpg'
$name = basename($path); // $name == '1.jpg'

Also, dirname() fetches the other part

$dir = dirname($path); // $dir == 'public/images/portfolio/i-vis'

If you need even more information - there is pathinfo()

$info = pathinfo($path);
var_dump($info);

produces

array(4) {
    ["dirname"]=>
    string(29) "public/images/portfolio/i-vis"
    ["basename"]=>
    string(5) "1.jpg"
    ["extension"]=>
    string(3) "jpg"
    ["filename"]=>
    string(1) "1"
}

So $info['filename'] gives you the file without the extension.




回答2:


echo basename($string);

Take a look at the basename function.




回答3:


alternative solution. Just a bunch of explodes

$str='public/images/portfolio/i-vis/1.jpg';
$s = end(explode("/",$str));
print "filename " . $s."\n";
$e = explode(".", $s );
print "without extension: $e[0]\n";


来源:https://stackoverflow.com/questions/1808553/find-the-filename-from-a-string-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!