Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using preg_replace for extract and wrapping purposes, but it's not outputting anything.

preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str) 
like image 932
Polsonby Avatar asked Aug 05 '08 00:08

Polsonby


People also ask

How to use preg_ match in PHP?

PHP | preg_match() Function. This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.

What is the difference between Str_replace and Preg_replace?

str_replace replaces a specific occurrence of a string, for instance "foo" will only match and replace that: "foo". preg_replace will do regular expression matching, for instance "/f. {2}/" will match and replace "foo", but also "fey", "fir", "fox", "f12", etc.

How preg match works?

Preg_match() function in php programming language work is based on searching the string pattern/patterns in the big list of string sentences or other and the preg_match() will return the TRUE value only if the string pattern is found or else the preg_match() function will return the FALSE value.


2 Answers

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

preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str) 
like image 168
Polsonby Avatar answered Sep 23 '22 02:09

Polsonby


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

like image 20
John Douthat Avatar answered Sep 22 '22 02:09

John Douthat