简体   繁体   中英

Removing Characters From String In Php

File Name

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

What I Need is

cars-lights-neon.jpg

What I Tried

$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";

This Code Also Works fine.. But it can be done in Simple steps..So What i am Asking is for better code..

//File Name and Resolution is coming from database so it is not same every time.. Thnx

Simply use preg_replace function of PHP like as

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

Demo

You can use preg_replace :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM