orobinec
orobinec

Reputation: 445

Preg_replace: enclosing found strings in brackets

I have a string which contains groups of numbers:

$test = "854 658+999";

I want to put each individual group in brackets using preg_replace… So far I have only found a way how to search for the numbers…

echo preg_replace('!\d+!',"(???)",$test);

What do I put instead of the question marks to get this?

(854) (658)+(999)

Upvotes: 1

Views: 110

Answers (1)

Nambi
Nambi

Reputation: 12042

Use the backreference in the replace parameter of preg_replace(). In the below statement, $1 is a backreference which contains what was captured by the capturing group (\d+) in your regex.

echo preg_replace("!(\d+)!", "($1)", $test);

Output:

(854) (658)+(999)

Upvotes: 3

Related Questions