tags:

views:

593

answers:

4

I am trying to grab the capital letters of a couple of words and wrap them in spans. I am using preg_replace, but it's not outputting anything.

preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str)
+13  A: 

You need to put the match in parentheses, like this:

preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str)
Flubba
Are you kidding me? You answered your own question just one minute later?
Gumbo
@Gumbo: Answering your own questions is perfectly fine, even encouraged, as long as the question isn't a duplicate of another one on the site.
Bill the Lizard
+1  A: 

From the preg_replace documentation on php.net:

replacement may contain references of the form \n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern.

See Flubba's example.

Wedge
+1  A: 

\0 will also match the entire matched expression without doing an explicit capture using parenthesis.

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

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

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

John Douthat
A: 

Use parentheses around your desired capture.

Dinah