Replace character by PHP function

1

I have to do a calculation based on 2 things:

1 - The value that the user informs

2 - The base account that I have registered with the bank

I have the base account: 5149.3074 * {{INPUT}} (0.0001) -5129.6906

Where is {{INPUT}} is the value that the user input in the input, until then I can replace {{INPUT}} with the value with the str_replace . The biggest problem is in " ^ " which means "Power" and for this PHP needs a function to calculate. What I need is to get the value that is after " ^ " in parentheses.

How can I do this?

    
asked by anonymous 15.06.2017 / 20:44

4 answers

3

You can use substring of php, like this:

$conta = "5149.3074*{{INPUT}}^(0.0001)-5129.6906";
$primeiro = strpos($conta, "(");
$segundo = strpos($conta, ")");
$valor = substr($conta, $primeiro + 1, $segundo - $primeiro - 1);

See working at Ideone .

Or do with Regex :

$conta = "5149.3074*{{INPUT}}^(0.0001)-5129.6906";
preg_match("/\(([^\]]*)\)/", $conta, $valor);

See working at Ideone .

    
15.06.2017 / 21:12
1

Using a simpler REGEX:

\(([0-9.]+)\)

This will allow any character between 0 to 9 ( 0-9 ) and points ( . ), in which case it would allow a 0...123 . But, I would not get any additional () . However, if you just want a single point (or none) you can use:

\(([0-9]+?(\.[0-9]+)?)\)

In general, it will be able to get all numbers before . , if it exists, and also the numbers after . , if it also exists.

The\(and\.aretoescape,since()and.isusedinREGEXforothercases.

Tests:

5149.3074*{{INPUT}}^(0.0001)-5129.6906=>0.0001(5149.3074*({{INPUT}}^(0.0001)))-5129.6906=>0.0001(5149.3074*({{INPUT}}^(((((((((0.0001)))))-5129.6906=>0.00015149.3074*{{INPUT}}^(1)-5129.6906=>15149.3074*{{INPUT}}^((((((1))))))-5129.6906=>15149.3074*{{INPUT}}^((((1)))))-5129.6906=>15149.3074*{{INPUT}}^((((1....123)))))-5129.6906=>Nãoencontrado

Try This

    
16.06.2017 / 01:47
0

Regular Expression: ideone

$conta = "5149.3074*{{INPUT}}^(0.0001)-5129.6906";
preg_match('^\((.*)\)^', $conta, $match);
print $match[1];

The circumflex marks the beginning of a line. ^\( means that the beginning must be by ( , the backslash serves to escape ( since it has a function in REGEX. The parentheses define a group, and their contents can be seen as a block in the expression (...) - indicates the beginning and end of a group respectively.

.   ponto       um caractere qualquer

*   asterisco   zero, um ou mais 

That is, within the parentheses we can have as many characters as there are.

About the function preg_match ()

  • The first parameter is the regular expression. ^\((.*)\)^
  • The second parameter is the string where we will search the expression. $conta
  • The third parameter is an array that will store the term that matched ($matches) .
  • 15.06.2017 / 22:24
    0

    Oops. I think you're looking for the exponential function to pow. var_dump(pow(2, 8)); // int(256) Retrieve pow function documentation for php

        
    16.06.2017 / 04:06