bashirudeen ahmad
bashirudeen ahmad

Reputation: 213

Find first negative number and prepend a zero

I want to insert a 0 before the first occurrence of - followed by a number.

I have tried the below simple code.

$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
preg_match('/^-?\d+(\.\d+)?$/', $formula, $match);

print_r($match);
$result = str_replace($match[0],'0'.$match[0],$formula);
echo $result;
exit;

I want the below result.

[ (((0-594 - 0) )/ 55032411) *244 ]

Upvotes: 0

Views: 73

Answers (3)

mickmackusa
mickmackusa

Reputation: 47874

No capture group is needed if you use a lookahead for a single digit. This is a pretty fast pattern.

Pattern: -(?=\d)

Pattern Demo

Code: (Demo)

$formula='[ (((-594 - 0) )/ 55032411) *244 ]';
var_export(preg_replace('/-(?=\d)/','0-',$formula,1)); // match -, prepend 0

Output:

'[ (((0-594 - 0) )/ 55032411) *244 ]'

Upvotes: 1

Andreas
Andreas

Reputation: 23958

Since I'm a firm believer that Regex != 42 I made a non regex that may work.
In short, it finds the first - in the string and saves the position.
Anything before this - is $part, but I use str_replace to remove all [() and space.
Then if this part is empty then there is no number before the first - so add the 0.

It's a bit complex but since it does not use regex it may be faster. But if you use other signs than [() and space in the start of calculation you need to add them in the arrays to remove.
Now that I think about it maybe +-/* should be there.

 $formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
 $pos = strpos($formula, "-");
 $part = str_replace(array("(",")","["," "), array("","","",""),substr($formula, 0, $pos));

If($part ==""){
     $formula = substr($formula, 0,$pos) ."0". substr($formula, $pos);
 }

Echo $formula;

I admit that it is complex, but I wanted to try to make a non regex solution.
https://3v4l.org/TaSjr

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using preg_replace function:

$formula = '[ (((-594 - 0) )/ 55032411) *244 ]';
$result = preg_replace('/-?\d+(\.\d+)?/', '0$0', $formula, 1);

print_r($result);

The output:

[ (((0-594 - 0) )/ 55032411) *244 ]

The 4th argument 1 passed to preg_replace is the maximum replacements for the pattern in the input string

Upvotes: 0

Related Questions