Cambiata
Cambiata

Reputation: 3845

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

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?

Upvotes: 16

Views: 11889

Answers (5)

Maxim Mandrik
Maxim Mandrik

Reputation: 447

For difficult regular expressions where you need to replace part of a string, it can be very useful to do so (and most importantly, you don't need to escape $newValue for the characters $ and \number):

$newValue = 'NewValue';

$newString = preg_replace_callback(
  '/(<Element>).*(<\/Element>)/',
  function($match) use ($newValue) { return $match[1].$newValue.$match[2]; },
  $string
);

Unreliable usage:

In preg_replace('/(<Element>).*(<\/Element>)/', '$1NewValue$2', $string): if instead of NewValue you need to put value from a variable that you do not control, then you need to escape the $ and \number characters, and this is quite a difficult task.

Upvotes: 0

Karsten
Karsten

Reputation: 14642

Do you really have to use regex for this?

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

Upvotes: 0

Douwe Maan
Douwe Maan

Reputation: 6878

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);

Upvotes: 3

Pentium10
Pentium10

Reputation: 207952

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.

Upvotes: 1

soulmerge
soulmerge

Reputation: 75714

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);

Upvotes: 15

Related Questions