0

I have values like so:

0.00000500
0.00003491
0.00086583
1.45304093

etc

I would like to run these through a PHP function so they become:

<span class="text-muted">0.00000</span>500
<span class="text-muted">0.0000</span>3491
<span class="text-muted">0.000</span>86583
1.45304093

What I have now is:

$input_number str_replace('0', '<span class="text-muted">0</span>', $input_number);
$input_number str_replace('.', '<span class="text-muted">.</span>', $input_number);

This is a bit 'aggressive' as it would replace every character instead of using the <span> once, but I guess that's OK, even if I have say 1000 numbers on a page. But the biggest problem I have is that my code would also 'mute' the last 2 digits in 0.00000500 which I don't want.

eskimo
  • 2,421
  • 5
  • 45
  • 81
  • Check out... https://stackoverflow.com/questions/19801385/php-find-the-number-of-zeros-in-a-decimal-number – MHewison Jun 15 '19 at 11:14

1 Answers1

0

First of all:

$input_number = str_replace('0.', '', $input_number);

We are replacing 0. with empty string

Secondly:

Use preg replace()

$newNumber = preg_replace('/^0?/','<span class="text-muted">0</span>',$input_number);

Basically /^0?/ is looking for leading 0's which will replace with span, you can also replce with empty or anything you want.

  • The result here is `000003491` so two errors: the period (.) is not there anymore, and it does not produce the desired result (all zero's have the ``) – eskimo Jun 15 '19 at 12:25