Basically, I want to replace certain words (for example, the word "tree" with the word "pizza") in sentences. Restriction: when the word to be replaced is between double quotes, the replacement must not be performed.
Example:
The tree is green. -> REPLACE tree WITH pizza
"The" tree is "green". -> REPLACE tree WITH pizza
"The tree" is green. -> DONT REPLACE
"The tree is" green. -> DONT REPLACE
The ""tree is green. -> REPLACE tree WITH pizza
Can this be done with regular expressions? I would count the number of double quotes before the word and check if it is odd or even. But is this possible using preg_replace in php?
Thanks!
// EDIT:
At the moment, my code is as follows:
preg_replace("/tree/", "pizza", $sentence)
But the problem here is the implementation of double-quoted logic. I tried things like:
preg_replace("/[^"]tree/", "pizza", $sentence)
, , . , .
- , .