For a custom script parser in PHP I would like to replace some words in a multiline string that contain double and single quotes.
However, only the text that is outside the quotes can be replaced.
Many apples are falling from the trees.
"There's another apple over there!"
'Seedling apples are an example of "extreme heterozygotes".'
For example, I would like to replace ‘apple’ with ‘pear’, but only outside the quote sentences. So in this case only ‘apple’ inside ‘Many apples are falling from the trees’ would be targeted.
The above would give the following output:
Many pears are falling from the trees.
"There's another apple over there!"
'Seedling apples are an example of "extreme heterozygotes".'
How can I achieve this?
This function does the trick:
How it works It splits by quoted strings but includes these quoted strings, this gives you alternating non-quoted, quoted, non-quoted, quoted etc strings in an array (some of the non-quoted strings may be blank). It then alternates between replacing the word and not replacing, so only non-quoted strings are replaced.
With your example
Output