0

Why do I get the extra "3" in this replacement?

$s='This is 3a and 3b';

$pattern='/3([a-z])/';
$replace='[$0]';

preg_replace($pattern, $replace, $s) gives 'This is [3a] and [3b]'

I thought $0 refers only to the match in the parenthesis. Same with $replace='[\0]';
I want: 'This is [a] and '

Thanks for any help, no doubt something trivial!

1
Contributor
1
Reply
2
Views
6 Years
Discussion Span
Last Post by spacific
1

OK, solved it myself!
I realise now that $0 refers to the whole matched pattern and $1 to the first match subpattern. So what I needed was $1 instead of $0.
Simple really, but that took me two hours to figure.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.