How can I get at the matches when using preg_replace in PHP?

Solution 1:

You need to put the pattern in parentheses /([A-Z])/, like this:

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

Solution 2:

\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.