Adding strings from a regular expression

Asked

Viewed 343 times

3

Good evening, I would like to find a way to add two strings within 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 doing some research, but I haven’t found any way to do that.

2 answers

1

<?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;
?>

By 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 answer

Although correct and despite working on many versions of Php, the option /e was discontinued from the Php7 version so it is not a good way to go...

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
);
  • @Andersoncarloswoss, thank you. Opps, I seem to have an older version... (PHP 5.6.9-1 )

  • Parse error: syntax error, Unexpected '$m' (T_VARIABLE) in [...][...] on line 10 LINE 10 >>> Function($m){retrun $m[0]. ($m[1]+$m[2]); },

  • @Leocaracciolo, thank you, no more wine for this glass: "Return" and not "retrun"...

  • hehehe, has more Notice: A non well Formed Numeric value encountered in [...][...] on line 10

  • test here http://sandbox.onlinephpfunctions.com/

  • @Leocaracciolo, thanks for the suggestion: help!. It worked well with me. (do not forget to replace "," by "." included in the initial reply)

  • show, now yes I can give +1 :) https://ideone.com/unD8bq

Show 2 more comments

0

Unable to perform with options Regex. Regular expressions serve basically to identify and return certain values.

In your case, besides the Regex, is to 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 that 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)));
}
  • ideone - https://ideone.com/5SOyDx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.