Saswat Saswat - 4 months ago 12
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
,
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?

Answer

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

Comments