Saswat Saswat - 6 months ago 15
PHP Question

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

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
from the

How can I overcome this issue?


You can use preg_replace() like below:-

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

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


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

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