如何使用 preg_replace 更改前 2 个字母的颜色

How to change color of first 2 letters using preg_replace

这是我的代码,但它只更改字符串的第一个字符

$string = 'Earrold Imperial Valdez';

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

取2个字符,例如

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

或者如果你想不使用正则表达式,你可以使用 substr(),例如

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

错误出在您的正则表达式中。 [a-z] 只会影响一个字符,因为没有乘数。要更改前 2 个,您需要使用量词 - {}

将您的 RegExp 更改为 /\b[a-z]{2})/i 应该可以解决问题。