Basically I want to replace certain words (e.g. the word
"tree" with the word "pizza") in sentences. Restriction: When the word that should be
replaced is between double quotes, the replace should 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
Is it possible
to do this 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 looks like the
following:
preg_replace("/tree/",
"pizza",
$sentence)
But the
problem here is to implement the logic with the double quotes. I tried things
like:
preg_replace("/[^"]tree/",
"pizza",
$sentence)
But
this does not work, because it checks only if a double quote is in front of the word.
But there are examples above where this check fails.
Import is that I want to
solve that problem with regex only.
No comments:
Post a Comment