Skip to content
Advertisement

Find and Replace Multi-Row Phrases/text Within PHP Arrays without damaging the array

Lets say I have an array:

JavaScript

Keeping the structure of this array intact, I want to be able to replace phrases within it, even if they spill over to the next or previous string. Also I don’t want punctuation or case to impact it.

Examples:

String to Find: “Sundays which are also pretty good”

Replace with: “Mondays which are also pretty great”

After replace:

JavaScript

Curious if there is an ideal way of doing this. My original thought was, I would turn the array into a string, strip out punctuation and spaces, count the characters and replace the phrase based on the character count. But, it is getting rather complex, but it is a complex problem

Advertisement

Answer

This is a job for regular expressions.

The method I used was to implode the array with some glue (i.e. '&'). Then I generated a regular expression by inserting a zero-or-one check for '&' in between each character in the find string.

I used the regular expression to replace occurrences of the string we were looking for with the replacement string. Then I exploded the string back into an array using the same delimiter as above ('&')

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement