-1

If you have this string:

$str = ';s:27:"2018/08/hello-there-003.jpg";s:5:"sizes";a:23:{s:9:"thumbnail";a:4:{s:4:"file";s:27:"hello-there-003-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:27:"hello-there-003-300x200.jpg"';

Is it possible to get all jpgs from it and replace it to something else?

The matches should be:

hello-there-003-150x150.jpg
hello-there-003-300x200.jpg

And replaced to:

replacement.jpg
replacement.jpg

So resulting string is:

 $str = ';s:27:"2018/08/replacement.jpg";s:5:"sizes";a:23:{s:9:"thumbnail";a:4:{s:4:"file";s:27:"replacement.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:27:"hello-there-003-300x200.jpg"';
Sometip
  • 332
  • 1
  • 10
  • 1
    https://regex101.com/ Simpler regular expressions are better. Maybe parse the string into tokens, massage key parts, and reassemble the tokens. –  Oct 17 '18 at 20:48
  • **(?<=\")[a-z\-\d]+.jpg** https://regex101.com/r/2xgKUz/1, i can add as answer if it works for you. For replacing it, you will do it coding, that's on you. – lucas_7_94 Oct 17 '18 at 20:49
  • 1
    looks like a broken sterilised array –  Oct 17 '18 at 20:52
  • Lucas, that works perfect! but how would you then replace the results within the string? Oh you said that's on me, what is the approach though, is it a foreach loop and str_replace? – Sometip Oct 17 '18 at 20:57
  • This looks very much like a serialized string. If you access it as a string rather than deserializing and access each data point correctly you are likely to corrupt the data for future processing. e.g. `27` before `2018/08/hello-there-003.jpg` is because there are 27 characters there. – user3783243 Oct 17 '18 at 21:06
  • This question is too general. – cellepo Oct 18 '18 at 02:04

1 Answers1

0

For your example data, you might use:

"\K[\w-]+(\.jpg)(?=")

Regex demo

Replace with

replacement$1

Explanation

  • " Match "
  • \K forget what was matched
  • [\w-]+ Match 1+ times a word character or a hyphen
  • (\.jpg) Match .jpg in a capturing group
  • (?=") Positive lookahead to assert what is on the right side is a double quote

For example:

$re = '/"\K[\w-]+(\.jpg)(?=")/';
$str = ';s:27:"2018/08/hello-there-003.jpg";s:5:"sizes";a:23:{s:9:"thumbnail";a:4:{s:4:"file";s:27:"hello-there-003-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:27:"hello-there-003-300x200.jpg"
';
$subst = 'replacement$1';
$result = preg_replace($re, $subst, $str);

echo $result;

Php demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70