Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php/regex: How to replace part of a found pattern, but leaving the rest as it is?

Tags:

regex

php

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?

like image 732
Cambiata Avatar asked Jan 24 '10 11:01

Cambiata


1 Answers

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);
like image 115
soulmerge Avatar answered Sep 30 '22 17:09

soulmerge