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)
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.
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.
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.
You need to put the pattern in parentheses /([A-Z])/
, like this:
preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str)
\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With