分享
三行代码  ›  专栏  ›  技术社区  ›  Yogesh Saroya

在php中只从字符串的最后一个删除最后一个数字

  •  -1
  • Yogesh Saroya  · 技术社区  · 5 天前

    mclaren-720s-exhaust-0.jpg
    mclaren-720s-exhaust-1.jpg
    mclaren-720s-exhaust-02.jpg
    mclaren-720s-exhaust-03.jpg
    

    现在我要将图像名转换为字符串,以便在ALT/TITLE上使用文本作为图像标记。

    1 回复  |  直到 5 天前
        1
  •  1
  •   GrumpyCrouton    5 天前

    你可以这样做 remove_last_number() 功能:

    function remove_last_number($file_string) {
    
        //remove extension from string
        $filename = substr($file_string, 0 , (strrpos($file_string, ".")));
    
        //break the filename by the `-` character, creating an array of each section
        $filename_parts = explode('-', $filename);
    
        //remove the last part of the filename, add it back if it contains any digits that aren't numbers
        $last_elem = array_pop($filename_parts);
        if (!preg_match("/^\d+$/", $last_elem)) {
            $filename_parts[] = $last_elem;
        }     
    
        //return correct filename by imploding all the parts back together and adding the extension.
        return implode(' ', $filename_parts);
    
    }
    

    用法:

    echo remove_last_number('mclaren-720s-exhaust-0.jpg');
    echo remove_last_number('mclaren-720s-exhaust-1.jpg');
    echo remove_last_number('mclaren-720s-exhaust-02.jpg');
    echo remove_last_number('mclaren-720s-exhaust-03.jpg');
    echo remove_last_number('mclaren-720s-exhaust-03d.jpg');
    

    mclaren 720s exhaust
    mclaren 720s exhaust
    mclaren 720s exhaust
    mclaren 720s exhaust
    mclaren 720s exhaust 03d
    
        2
  •  0
  •   SpinyMan    5 天前

    我只需添加下一个regex:

    $imageName = 'mclaren-720s-exhaust-02.jpg';
    $name = str_replace(
        '-', 
        ' ', 
        preg_replace('~(.+)\-[0-9]+\.\w{3,4}~', '$1', $imageName)
    );