How can I replace a substring in a found pattern, but leaving the rest as it is?
(EDIT: The real case is of course more complicated than the example below, I have to match occurrences within xml tags. That's why I have to use regex!)
Let's say I want to change occurrences of the letter "X" within a word to the letter "Z".
I want
aaXaa aaX Xaa
to become
aaZaa aaZ Zaa
Finding occurrences of words including "x" isn't a problem, like this:
[^X\s]X[^\s]
but a normal preg_match replaces the complete match, where I want anything in the pattern except "X" to stay as it is.
Which is the best way to accomplish this in php?
If your regex matches only the relevant part, it should be no problem that it replaces the complete match (like preg_replace('/X/', 'Z', $string)
).
But if you need the regex to contain parts that should not be replaced, you need to capture them and insert them back:
preg_replace('/(non-replace)X(restofregex)/', '$1Z$2', $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With