Amanda Thompson Amanda Thompson - 2 months ago 20
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:

<?php

$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

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>.

Comments