php – Sum strings from a regular expression

Question:

Good night, I would like to find a way to add two strings inside a regular expression using php . Ex:

$texto = "
|5,00|7,00||
|10,00|2,00||
|3,00|30,00||";

 

...('/\|(.*)\|(.*)\|/', '|$1|$2|[X=$1+$2]', $texto);

I've been searching, but I haven't found any way to do this.

Answer:

<?php
$texto = "
|5,00|7,00||
|10,00|2,00||
|3,00|30,00||";                       // "texto" da pergunta

$texto= str_replace(",",".",$texto);  // locales (ver @ValdeirPsr)

$b=preg_replace('/\|(.+?)\|(.+?)\|/e', '"$0" . ($1+$2) ', $texto );
echo $b;
?>

Replacing the second argument of preg_replace will contain strings like

"|5,00|7,00|" . (5,00 + 7,00)

which after being calculated give |5,00|7,00|12

Update: ignore this answer

Although correct and despite working on many Php versions, the /e option has been discontinued as of the Php7 version so it's not a good way forward…

I think that in the most recent versions the recommended would be

$b=preg_replace_callback(
    '/\|(.+?)\|(.+?)\|/',
    function($m){return $m[0]. ($m[1]+$m[2]); },
    $texto
);
Scroll to Top