Add strings to a regular expression

4

Good evening, 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 have not found any way to do this.

    
asked by anonymous 21.12.2017 / 03:53

2 answers

2
<?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 as

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

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

Update: Ignore this response

Although correct and although it works on many versions of Php, the /e option has been deprecated since the Php7 version so it is not a good way to go ...

I think that in the latest versions the recommended would be

$b=preg_replace_callback(
    '/\|(.+?)\|(.+?)\|/',
    function($m){return $m[0]. ($m[1]+$m[2]); },
    $texto
);
    
21.12.2017 / 13:59
1

Can not make choices with Regex . Regular expressions basically serve to identify and return certain values.

In your case, in addition to Regex , you use two functions of PHP : preg_match_all to capture the values in array and array_sum to add the captured arrays.

What would be more or less this way:

<?php

$regex = "([\d\.]+\|[\d\.]+)";
$value = str_replace(",", ".", "|5,50|7,00|| |10,0|2,00|| |3,00|30,0||");

preg_match_all("/{$regex}/", $value, $results);

foreach(reset($results) as $result) {
    $values = explode("|", $result);

    var_dump(sprintf("%s = %s", implode(" + ", $values), array_sum($values)));
}
    
21.12.2017 / 05:13