【问题标题】:Removing Characters From String In Php在 PHP 中从字符串中删除字符
【发布时间】:2015-11-18 09:15:19
【问题描述】:

文件名

cars-lights-neon-1920x1080.jpg
cars-lights-neon-3840x2160.jpg
cars-lights-neon-800x600.jpg

我需要的是

cars-lights-neon.jpg

我尝试了什么

$name="cars-lights-neon-1920x1080.jpg";
$newname =   substr($name, 0, -4); //removing.jpg
// Real name
$rev= strrev("$newname"); // outputs "0801x0291-noen-sthgil-srac"
$revok= strstr($rev, '-'); //outputs "-noen-sthgil-srac"
$neutral = strrev("$revok"); //outputs "cars-lights-neon-"
$neutral = substr($neutral, 0, -1); //outputs "cars-lights-neon"

$filename = $neutral.".jpg"; //outputs "cars-lights-neon.jpg";

此代码也可以正常工作..但可以通过简单的步骤完成..所以我要求的是更好的代码..

//文件名和分辨率来自数据库,所以每次都不一样.. 谢谢

【问题讨论】:

    标签: php string substring trim


    【解决方案1】:

    简单地使用preg_replace 像 as 的 PHP 函数

    $name = "cars-lights-neon-1920x1080.jpg";
    echo preg_replace('/(-\d+x\d+)/','',$name);//cars-lights-neon.jpg
    

    Demo

    【讨论】:

    • 一件事更多 cars-lights-neon-3840x2160.jpg 我还需要宽度和高度
      $width = "3840"; $height ="2160";
    • 只需使用preg_match('/-(\d+)x(\d+)/',$name,$m); print_r($m); Check This
    【解决方案2】:

    你可以使用preg_replace:

    $string = 'cars-lights-neon-1920x1080.jpg';
    $filename = preg_replace('/-[0-9]{3,4}x[0-9]{3,4}/', '', $string);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 2010-12-02
      • 2011-08-29
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多