How can I get matches when using preg_replace in PHP?

I am trying to capture uppercase letters from several words and wrap them in span tags. I use preg_replace to extract and wrap, but it doesn’t output anything.

preg_replace("/[AZ]/", "<span class=\"initial\">$1</span>", $str) 
+48
php regex html-parsing preg-replace
Aug 05 '08 at 0:35
source share
4 answers

You need to put the pattern in parentheses /([AZ])/ , for example:

 preg_replace("/([AZ])/", "<span class=\"initial\">$1</span>", $str) 
+50
Aug 05 '08 at 0:36
source share

\0 will also match the entire matched expression without explicit capture using parentheses.

 preg_replace("/[AZ]/", "<span class=\"initial\">\\0</span>", $str) 

As always, you can go to php.net/preg_replace or php.net/<whatever search term> quickly find documentation. Print the documentation:

\ 0 or $ 0 refers to the text matched by the entire pattern.

+25
Aug 28 '08 at 9:02
source share

From the preg_replace documentation on php.net :

the replacement may contain links to the form \ n or (starting with PHP 4.0.4) $ n, with the latter form being preferred. Each such link will be replaced by text captured in the nth bracket.

See Flubba example.

+8
Aug 05 '08 at 1:39
source share

Use brackets around the desired grip.

+6
Jun 23 '09 at 17:54
source share



All Articles