0

I want to replace all instances of a particular string in an object which includes properties, values and keys that include this string, including within longer keys/values that contain this string amongst other information.

Currently I'm doing this:

$amended_object = str_replace('search', 'replace', serialize($object));
$object = unserialize($amended_object);

So I turn the object into a string, search and replace, and convert it back.

However I often get Notice: unserialize(): Error at offset when the object is in a particular state, and it seems like it's not a very good solution.

lightsurge
  • 297
  • 5
  • 9
  • 2
    When you serialize you get something like `s:5:"value"` which means `string:length 5:"value"`. So if you change `value` to `bob` it is no longer length `5`. – AbraCadaver Feb 13 '18 at 19:57
  • 1
    Assuming the object is just a standard stdClass then you are much better off using `json_encode()` and `json_decode()`. Additionally If you are searching or replacing an escaped character then you need to respect it all the way through. – MonkeyZeus Feb 13 '18 at 19:58
  • Bahh, that was my answer... ^^^^^ Use this as it doesn't store types or lengths. – AbraCadaver Feb 13 '18 at 19:59
  • 1
    @AbraCadaver My comment was honestly just built as a continuation of yours. You succinctly explained why the error is occurring which is important :) – MonkeyZeus Feb 13 '18 at 20:03

2 Answers2

2

When you serialize you get something like s:5:"value" which means string:length 5:"value". So if you change value to bob it is no longer length 5 and unserialize will error.

So you would need to correct the string lengths as well. Try JSON as it doesn't store the types or lengths:

$amended_object = str_replace('search', 'replace', json_encode($object));
$object = json_decode($amended_object);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

Serialize wont work unless you correct the length of the containing string in the entity.

So you take the substring of the entity, split it up by the : sign, count/get the length of the total value string you want to correct and recalculate that with your replacement considered. Then update the stringcontent.

Stephan
  • 41
  • 5
  • json_encode (from other answers) wouldn't work for me I think because of the complexity of the object. Correcting the lengths as with your answer worked fine though. Check here for a snippet to recalculate: https://stackoverflow.com/a/5581004/7253130 – lightsurge Feb 13 '18 at 20:07
  • I remember that one but couldn't find it as a duplicate. – AbraCadaver Feb 13 '18 at 20:10