-4

Sorry for my bad English in Advance. Here is my JSON return.

https://images-na.ssl-images-amazon.com/images/M/MV5BYzc3OGZjYWQtZGFkMy00YTNlLWE5NDYtMTRkNTNjODc2MjllXkEyXkFqcGdeQXVyNjExODE1MDc@._V1_UY268_CR5,0,182,268_AL_.jpg

How can I remove the part UY268_CR5,0,182,268_AL_. Specifically that part only. And I have many of this links. Each having different strings there. For example:

https://m.media-amazon.com/images/M/MV5BYWNlMWMxOWYtZWI0Mi00ZTg0LWEwZTMtZTEzZDY0NzAxYTA4XkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_UX182_CR0,0,182,268_AL_.jpg

As shown it is different. I want to remove the part UX182_CR0,0,182,268_AL_. Each of the results I have has almost the same structure but the end part I want to remove. I am on laravel and so I am encoding my jsons result from controller. Is there anyone this can be done with php?

Update:

Here is the code I tried.

$json = json_decode($data,true);

    $slice = str_replace("UY268_CR5,0,182,268_AL_","", $json);

    return $slice ['poster'];

The string is removed but what about different strings with different URL's like mentioned above?

Marwelln
  • 28,492
  • 21
  • 93
  • 117
RESIP
  • 1
  • 2

1 Answers1

0

You can try with preg_replace() with the combination of lookahead and lookbehind

<?php
$re = '/(?<=_V1_)(.+?)(?=.jpg)/';
$str = 'https://m.media-amazon.com/images/M/MV5BYWNlMWMxOWYtZWI0Mi00ZTg0LWEwZTMtZTEzZDY0NzAxYTA4XkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_UX182_CR0,0,182,268_AL_.jpg';
$subst = '';

$result = preg_replace($re, $subst, $str, 1);
echo "The result of the substitution is ".$result;

?>

DEMO: https://eval.in/1044470

REFF: Regex lookahead, lookbehind and atomic groups

REGEX EXPLANATION: https://regex101.com/r/aHAw5f/1

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • Sorry I can not vote up but this works! Accepted! one more question if you dont mind. Can you explain this? `/(?<=_V1_)(.+?)(?=.jpg)/`. I mean can you explain what those strings are? – RESIP Aug 03 '18 at 16:12
  • @RESIP. glad it works for you and help you somehow. I've updated my answer with some cool and informative references. You can see the explanation of `(?<=_V1_)(.+?)(?=.jpg)` on the right side of *EXPLANATION* section on https://regex101.com/r/aHAw5f/1 site. Best of luck – A l w a y s S u n n y Aug 03 '18 at 16:18
  • 1
    Ok I figured it out. The explanation was very useful. Thanks a bunch :) – RESIP Aug 03 '18 at 16:24