使用PHP,我想比较两个文件的扩展名,如果它们不相同,则将一个文件的扩展名替换为另一个文件的扩展名。我知道如何使用多行来实现它,但我想知道是否有任何方法可以用几行来做到这一点?
$first_file='/path/to/the/first/';
$second_file='/path/to/the/second/';
$type1 = strtolower(substr(strrchr($first_file,"."),1));
$type2 = strtolower(substr(strrchr($second_file,"."),1));
if($type2=='')
{
$second_file.=".$type1";
}
else if($type2!==$type1)
{
$second_file='second_file with its type replaced by the type1';
}
感谢
答案 0 :(得分:1)
您可以使用pathinfo函数获取必要的信息并替换扩展名,如下所示:
$first_file='path/asdf/rand.txt';
$second_file='path/asdf/random.png';
$info1 = pathinfo($first_file);
$info2 = pathinfo($second_file);
define('DS', DIRECTORY_SEPARATOR);
if($info2['extension']!==$info1['extension'])
{
$second_file= $info2['dirname'].DS.$info2['filename'].'.'.$info1['extension'];
}