How to manipulate a string so that I can make implicit multiplication explicit in a mathematical expression?

I want to manipulate a string like "... 4 + 3 (4-2) -...." to become "... 4 + 3 * (4-2) -....", but of course it should recognize any number , d, and then '(' and change it to 'd * ('. And I also want to change ') (' to ') * (' at the same time, if possible. It would be nice if you had the opportunity to add support for constants, such as pi or e.

At the moment, I'm just doing this stupidly:

private function make_implicit_multiplication_explicit($string)
{
    $i=1;
    if(strlen($string)>1)
    {
        while(($i=strpos($string,"(",$i))!==false)
        {
            if(strpos("0123456789",substr($string,$i-1,1))) 
            {
                $string=substr_replace($string,"*(",$i,1);
                $i++;
            }
            $i++;
        }

        $string=str_replace(")(",")*(",$string);
    }        
    return $string;
 }

But I believe that this can be done much better with preg_replace or some other regular expression function? But these guides are really cumbersome, I think.

+4
4

, :

  • : ((a|b) a, b)
    • , \d
    • ): \)
  • (: \(

: (\d|\))\(. , \(, (\(), , .

, , , : \\1*\\2,

$regex = "/(\d|\))(\()/";
$replace = "\\1*\\2";
$new = preg_replace($regex, $replace, $test);

, , . .

+5

, ( )( , lookaround .

echo preg_replace("/

         (?<=[0-9)])   # look behind to see if there is: '0' to '9', ')'
         (?=\()        # look ahead to see if there is: '('

         /x", '*', '(4+3(4-2)-3)(2+3)'); 

Lookbehind , - . Positive Lookahead , .

- escape- \K Lookbehind. \K . ( , ).

echo preg_replace("/

         [0-9)]   # any character of: '0' to '9', ')'
          \K      # resets the starting point of the reported match
          (?=\()  # look ahead to see if there is: '('

         /x", '*', '(4+3(4-2)-3)(2+3)'); 
+4

php- ,

<?php
$mystring = "4+3(4-2)-(5)(3)";
$regex = '~\d+\K\(~';
$replacement = "*(";
$str = preg_replace($regex, $replacement, $mystring);
$regex1 = '~\)\K\(~';
$replacement1 = "*(";
echo preg_replace($regex1, $replacement1, $str);
?> //=>  4+3*(4-2)-(5)*(3)

:

  • ~\d+\K\(~ , (. -\K \d +
  • Again, it replaces the agreed part *(, which, in turn, creates 3*(, and the result is stored in another variable.
  • \)\K\(Matches )(and excludes the first ). This will be replaced by *(, which, in turn, produces)*(

Demo 1

Demo 2

+3
source

Stupid Method: ^)

$value = '4+3(4-2)(1+2)';

$search = ['1(', '2(', '3(', '4(', '5(', '6(', '7(', '8(', '9(', '0(', ')('];
$replace = ['1*(', '2*(', '3*(', '4*(', '5*(', '6*(', '7*(', '8*(', '9*(', '0*(', ')*('];

echo str_replace($search, $replace, $value);
0
source

Source: https://habr.com/ru/post/1546638/


All Articles