Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex for math operations

Tags:

regex

php

So i'm trying to create a regex without success.

This is what i get as in input string:

String A: "##(ABC 50a- {+} UDF 69,22g,-) {*} 3##"
String B: "##ABC 0,10,- DEF {/} 9 ABC {*} UHG 3-##"

And this is what i need processed out of the regex:

Result A: "(50+69,22)*3"
String B: "0,10/9*3"

I just can't get the number replacement combined with the operation symbols.

This is what i got:

'/[^0-9\+\-\*\/\(\)\.]/'

Thankful for every help.

like image 752
Mike Avatar asked Mar 27 '26 04:03

Mike


1 Answers

One simple solution consists of getting rid of everything you don't want.

So replace this:

\{(.+?)\}|[^0-9,{}()]+|(?<!\d),|,(?!\d)

With $1.

Simple enough:

$input = "(ABC 50a- {+} UDF 69,22g,-) {*} 3";
$output = preg_replace('#\{(.+?)\}|[^0-9,{}()]+|(?<!\d),|,(?!\d)#', '$1', $input);
  • \{(.+?)\} part matches everything inside {...} and outputs it (it gets replaced by $1)
  • [^0-9,{}()]+ gets rid of every character not belonging to the ones we're trying to keep (it's replaced with an empty string)
  • (?<!\d),|,(?!\d) throws out commas which are not part of a number

Unfortunately, I can't say much else without a better spec.

like image 71
Lucas Trzesniewski Avatar answered Mar 28 '26 16:03

Lucas Trzesniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!