0

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?

9
  • 4
    $filename=str_replace('thumb_','',$filename); ? Commented Jul 18, 2016 at 7:00
  • your variable have comma separated value? Commented Jul 18, 2016 at 7:01
  • @RamRaider and what if the string contains 'thumb_' in the middle, but not on the left? Commented Jul 18, 2016 at 7:01
  • @Anant Precisely, no. It doesn't contain comma separated values. Commented Jul 18, 2016 at 7:02
  • 3
    $filename=preg_replace('/^thumb_/','',$filename); Commented Jul 18, 2016 at 7:03

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

You have to use not true, and using a regex for something like this often leads to problems, as regexes are so often misunderstood.
In this case we have to use regex, as we only require to remove sub-string at the beginning of the string. preg_replace('/^thumb_/','',$data)
@anant, you can't use str_replace. Run your code for the value 8_2393_thumb_Shades 1.jpg
1

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.