简体   繁体   中英

How to remove a string from left side of a bigger string in PHP?

I have a variable which can send me data like:-

thumb_8_2393_Shades 1.jpg , hanger-cloth.jpg & Red-Lehenga-1.jpg ;

Now, when the value will have 'thumb_' at the left side, I want to discard the 'thumb_' string from the full value.

So I wrote this code:-

$pImgBig = trim($pI['image'],'thumb');

What the issue I am facing is, it is also removing the 'h' from the 'hanger-cloth.jpg' .

How can I overcome this issue?

You can use preg_replace() like below:-

$pImgBig = preg_replace('/^thumb_/','',$pI['image']);

<?php
$data = 'hanger-cloth.jpg';

$data = preg_replace('/^thumb_/','',$data);
echo $data;

$data1 = 'thumb_8_2393_Shades 1.jpg';

$data1 = preg_replace('/^thumb_/','',$data1);
echo $data1;

Output:- https://eval.in/606785

@RaimRaider give a very nice sugestion of using str_replace() in correct way like below:-

<?php
$data = 'hanger-cloth.jpg';

$data =  substr($data,0,6)==='thumb_' ? str_replace( 'thumb_', '', $data ) : $data;
echo $data;

$data1 = 'thumb_8_2393_Shades 1.jpg';

$data1 =  substr($data1,0,6)==='thumb_' ? str_replace( 'thumb_', '', $data1 ) : $data1;
echo $data1;

$filename=substr($filename,0,6)==='thumb_' ? str_replace( 'thumb_', '', $filename ) : $filename;

Output:- https://eval.in/606800

The solution using strpos and substr functions:

$images = ['thumb_8_2393_Shades 1.jpg','hanger-cloth.jpg', 'Red-Lehenga-1.jpg'];
foreach ($images as &$img) {
    if (strpos($img, 'thumb_') === 0) {  // if file name starts with 'thumb_'
        $img = substr($img, 6);
    }
}

print_r($images);

The output:

Array
(
    [0] => 8_2393_Shades 1.jpg
    [1] => hanger-cloth.jpg
    [2] => Red-Lehenga-1.jpg
)

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