php删除图像扩展名首先转换为字符串或只是数组

时间:2014-03-27 07:14:56

标签: php

$d是一个数组Array ( [0] => image1.jpg [1] => image3.jpg [2] => image2.jpg [3] => stores1.jpg [4] => stores2.jpg [5] => stores2.jpg [6] => stores3.jpg [7] => stores4.jpg [8] => design1.jpg [9] => design2.jpg ) ;

我可以将所有文件名作为字符串

$d = '';
foreach($d as $value){
     $d .= '"'.$value.'",';
}
echo $d;

我得到了

"image1.jpg","image3.jpg","image2.jpg","stores1.jpg","stores2.jpg","stores2.jpg","stores3.jpg","stores4.jpg","design1.jpg","design2.jpg",

如何删除所有.jpg

"image1","image3","image2","stores1","stores2","stores2","stores3","stores4","design1","design2",

我想知道在转换为字符串之前或转换之后是否需要删除所有.jpg。感谢

3 个答案:

答案 0 :(得分:1)

您只需使用空字符串

替换目标文件扩展名即可
function remove_extensions_from_array(array $files){

   $result = array();

   foreach($files as $file) {
      // Grab target extension
      $extension = pathinfo($file, PATHINFO_EXTENSION);

      // Replace it with an empty string and push into $result array
      $result[] = str_replace(array('.', $extension), '', $file);
   }

   return $result;
}

这几乎适用于任何扩展(不仅仅是.jpg),因为扩展名没有紧密耦合

答案 1 :(得分:1)

你可以简单地使用explode

$testarrays = array ('image1.jpg', 'image2.jpg', 'image3.jpg' );

foreach ($testarrays as $key=>$value){
    $temp = explode(".", $value);
    $filename[$key] = $temp[0];
}


print_r($filename);

答案 2 :(得分:0)

array_walk会有所帮助

array_walk($arr,function (&$v){ $v = basename($v,'.jpg');});

代码

<?php
$arr=array("image1.jpg","image3.jpg","image2.jpg","stores1.jpg","stores2.jpg","stores2.jpg","stores3.jpg","stores4.jpg","design1.jpg","design2.jpg");
array_walk($arr,function (&$v){ $v = basename($v,'.jpg');});
print_r($arr);

<强> OUTPUT :

Array
(
    [0] => image1
    [1] => image3
    [2] => image2
    [3] => stores1
    [4] => stores2
    [5] => stores2
    [6] => stores3
    [7] => stores4
    [8] => design1
    [9] => design2
)

<强> EDIT :

  

如果我只想保留前4个字母&#39; imag&#39;,&#39; stor&#39;什么方法   我应该用吗?

将之前的array_walk替换为新的array_walk

array_walk($arr,function (&$v){ $v = substr($v,0,4);});