Amanda Thompson Amanda Thompson - 1 year ago 101
PHP Question

Regex to match accents, spaces

How can I replace the text, for example: c2stackoverflow to

span style="color:#ffdc50">stackoverflow</span>'

I try to do this:


$string = "c2stackoverflow";
$string = preg_replace("/c2([A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ])+$/", '<span style="color:#ffdc50">$1</span>', $string);
echo $string;

But the output is:

<span style="color:#ffdc50">w</span>

Answer Source

Since your original regex shows (by its final $) that you want to replace the entire remainging set of characters after c2, you may simply use this:

$string = preg_replace("/c2(.*)$/", '<span style="color:#ffdc50">$1</span>', $string);

Note that I replaced + by * so even a string like c2 will be replaced by <span style="color:#ffdc50"></span>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download