preg_replace last character

199 Views Asked by At

I have a code which works need to make red only the last two letters

$text = '£5,485.00';
$text = preg_replace('/(\b[a-z])/i','<span style="color:red;">\1</span>',$text);
echo $text;

need like this enter image description here

1

There are 1 best solutions below

0
hakre On

taken your question verbatim:

preg_replace('/\w{2}$/','<span style="color:red;">\0</span>', $text);
               ^^^^^^                             ^^
   \w{2} : two word characters               \0 : main matching group
   $     : anchored at the end

You may want to support Unicode (/u - u modifier) and prevent the $ to match end-of-string and new-line at end-of-string (/D - D modifier):

  • u (PCRE_UTF8)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8. An invalid subject will cause the preg_* function to match nothing; an invalid pattern will trigger an error of level E_WARNING. Five and six octet UTF-8 sequences are regarded as invalid.

  • D (PCRE_DOLLAR_ENDONLY)

If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.