分解 PHP 中的文件名以使用其中的一部分

Explode filename in PHP to use parts of it

我想显示存储在数组中的部分文件名。 目前,我正在使用这样的文件名:

Brand-Product-Variation-ID-EAN-SKU-1.jpg
Brand-Product-EAN-SKU-24.jpg
Brand-Product-SKU-100.jpg

我需要这种格式的文件名:

Brand-Prdocut-Variation-ID-EAN-SKU-{col}.jpg

文件名可能不同,或多或少带有“-”。所以我总是需要最后一个“-”之后的文件名的最后一个数字。

我知道 PHP 中有一个函数可以分解文件名或文本。 但是不知道最后一个“-”怎么用。

您可以使用 php explode

// it will return  an array of '-' seperated values
  $arr= explode('-' , 'Brand-Prdocut-Variation-ID-EAN-SKU-1.jpg');

  // it will return  the index value which is  "1.jpg" in your case 
 $val = end($arr)
  $arr = explode('.' , $val);

 // this is your answer in the col which is "1" in your case
    $col = $arr[0];

获取最后一个“-”之前的部分

$arr = explode('-' , 'Brand-Prdocut-Variation-ID-EAN-SKU-1.jpg');  
$val  = $arr[ count($arr) -1 ];

// $val this is your value before the last "-"
$ss="Brand-Product-SKU-100.jpg";
preg_match("/[A-Za-z-]{1,100}-([0-9]{1,5}).[A-Za-z]{1,3}/",$ss,$kk);
echo "<pre>";
print_r($kk);
echo "</pre>";

100 表示文件名的最大长度。 (最大长度 "Brand-Product-SKU-100") 5:例如我们想要获得的数字的最大长度(最大长度为“100”) 1,3:长度文件扩展名可以是1或2或3

结果:

Array
(
    [0] => Brand-Product-SKU-100.jpg
    [1] => 100
)