Search code examples
phpregexpreg-replacecurrency-formattingreformatting

Parse HTML and reformat dollar amount in tag with specific class


I can't fix my code.

<?
$tabla = "<table>
<tr>
<td>
<a class='texto'>$ 2,123.01</a>
</td>
<td>
asddasdsad$,.$$$
</td>
</tr>
</table>";
echo preg_replace("<a class='texto'>\$ ([0-9]*),([0-9]*).([0-9]*)</a>", "<a class='texto'>$0$1,$2</a>", $tabla);

?>

PHP Error: Warning: preg_replace() [function.preg-replace]: Unknown modifier '$'

I would like to get:

<?
<table>
<tr>
<td>
<a class='texto'>2123,01</a>
</td>
<td>
asddasdsad$,.$$$
</td>
</tr>
</table>
?>

I tried & tested my regular expression here http://regexpal.com/ and worked, but I have something wrong in preg_replace().


Solution

  • You have three mistakes:

    1. \$ inside the double quotes means just $ which is treated by regex as match to end-of-line
    2. You forgot pattern delimiters
    3. $0 refers to the whole string. Expressions in parenthesis are referred to as $1, $2, etc.
    
    echo preg_replace("|<a class='texto'>\\\$ ([0-9]*),([0-9]*).([0-9]*)</a>|", "<a class='texto'>$1$2,$3</a>", $tabla);