tags:

views:

52

answers:

4

Hi!

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 occurances within xml tags. That's why I have to use regex!)

Let's say I want to change occurances of the letter "X" within a word to the letter "Z".

I want

aaXaa aaX Xaa

to become

aaZaa aaZ Zaa

Finding occurances 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.

Wich is the best way to accomplish this in php?

+2  A: 

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);
soulmerge
Thank you, Soulmerge! Exactly what I needed!
Cambiata
A: 

Try this

<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The bear black slow jumped over the lazy dog.
Pentium10
+1  A: 

If it's really as simple as replacing X with Z, you can also use str_replace(), which is faster than using preg in this case:

$sNew = str_replace("X", "Z", $sOld);
Douwe Maan
I get your point, and the real case is of course more complicated. I will use it for handling namespace tags in xml-documents, so there has to be real regex for this!
Cambiata
A: 

Do you really have to use regex for this?

$output = str_replace('X', 'Z', $input);
Karsten