Thomas Owens
Thomas Owens

Reputation: 116179

How do you use back-references to PCREs in PHP?

I read this PHP RegEx page, but either I'm missing something, misreading something, or it doesn't work the way they say. I'm guessing it's one of the first two.

$str = preg_replace("([|]\d*)", "\1;", $str);

Upvotes: 3

Views: 1400

Answers (1)

Vegard Larsen
Vegard Larsen

Reputation: 13047

Your regular expression should follow Perl syntax, meaning it has to start and end with the same character (with some exceptions). Also, the back reference should start with a double slash, to get around PHPs double escaping. This should work (with a quick test):

$str = "asdfasdf |123123 asdf iakds |302 asdf |11";
$str = preg_replace("/([|]\d*)/", "\\1;", $str);
echo $str; // prints "asdfasdf |123123; asdf iakds |302; asdf |11;"

Upvotes: 4

Related Questions