Earrold
Earrold

Reputation: 21

How to change color of first 2 letters using preg_replace

Here is my code but it only change first character of the string

$string = 'Earrold Imperial Valdez';

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

Upvotes: 1

Views: 1512

Answers (2)

Ben Kolya Mansley
Ben Kolya Mansley

Reputation: 1793

The error is in your Regex. [a-z] will only affect one character, because there's no multiplier. To change the first 2, you'll need to use a quantifier - {}.

Changing your RegExp to /\b[a-z]{2})/i should fix it.

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

Just take 2 character, e.g.

$text = preg_replace('/^([a-z]{2})/i','<span style="color:red;">\1</span>',$string);  
                     //↑      ^^^ Quantifier: {2} Exactly 2 time
                     //| assert position at start of the string

Or if you want to do it without regex, you can use substr(), e.g.

$text = '<span style="color:red;">' . substr($string, 0, 2) . '</span>' . substr($string, 2);  

Upvotes: 1

Related Questions