user701510
user701510

Reputation: 5763

preg_replace() seems to remove entire word instead of part of it

I'm trying to match a certain word and replace part of the word with certain text but leave the rest of the word intact. It is my understanding that adding parentheses to part of the regex pattern means that the pattern match within the parentheses gets replaced when you use preg_replace()

for testing purposes I used:

$text = 'batman';
echo $new_text = preg_replace('#(bat)man#', 'aqua', $text);

I only want 'bat' to be replaced by 'aqua' to get 'aquaman'. Instead, $new_text echoes 'aqua', leaving out the 'man' part.

Upvotes: 0

Views: 1837

Answers (4)

Treffynnon
Treffynnon

Reputation: 21553

I would not use preg_* functions for this and just do str_replace() DOCs:

echo str_replace('batman', 'aquaman', $text);

This is simpler as a regex is not really needed in this case. Otherwise it would be with a regular expression:

echo $new_text = preg_replace('#bat(man)#', 'aqua\\1', $text);

This will substitute your man in after aqua when replacing the entire search phrase. preg_replace DOCs replaces the entire matching portion of the pattern.

Upvotes: 3

Ayman Safadi
Ayman Safadi

Reputation: 11552

The way you're trying to do it, it would be more like:

preg_replace('#bat(man)#', 'aqua$1', $text);

I'd using positive lookahead:

preg_replace('/bat(?=man)/', 'aqua', $text)

Demo here: http://ideone.com/G9F4q

Upvotes: 2

stema
stema

Reputation: 92976

The brackets are creating a capturing group, that means you can access the part matched by this group using \1.

you can do either what zerkms suggested or use a lookahead that does just check but not match.

$text = 'batman';
echo $new_text = preg_replace('#bat(?=man)#', 'aqua', $text);

This will match "bat" but only if it is followed by "man", and only "bat" is replaced.

Upvotes: 1

zerkms
zerkms

Reputation: 254916

preg_replace replaces all the string matched by regular expression

$text = 'batman';
echo $new_text = preg_replace('#bat(man)#', 'aqua\\1', $text);

Capture man instead and append it to your aqua prefix

Another way of doing that is to use assertions:

$text = 'batman';
echo $new_text = preg_replace('#bat(?=man)#', 'aqua', $text);

Upvotes: 5

Related Questions