AVC
AVC

Reputation: 77

PHP - Simple Regular Expression

Consider the below code

$t = preg_replace('/0+$/','',".800000000000000"); //Replace last 0s

This gives me output as .8 as expected

Now consider the below code

$a = .80;
$t = sprintf('%.15f', $a)."<br>";
echo "First : $t<br>";
$t = preg_replace('/0+$/','',$t);
echo "Second : $t <br>";

This gives output as First : 0.800000000000000 Second : 0.800000000000000

Could you help me to find out why the last 0s are not replaced by regular expression in this case as the expected output is 0.8 ?

Upvotes: 0

Views: 44

Answers (3)

oezi
oezi

Reputation: 51797

your variable $t contains 0.800000000000000<br> so there ar no trailing zeros to cut off.

you'll have to shorten the string before appending <br>.

Upvotes: 1

Guillaume Poussel
Guillaume Poussel

Reputation: 9822

Since you are adding <br> to the end of $t with this line:

$t = sprintf('%.15f', $a)."<br>";

You regex no longer matches trailing 0. "<br>" is part of the presentation, you should add it at the very end.

Upvotes: 4

Pheonix
Pheonix

Reputation: 6052

You append a <br> tag at the end, while the Regex says 0's before end of line

'/0+$/'
    ^ <- end of line, nothing should come after 0's
".800000000000000"

$a = .80;
$t = sprintf('%.15f', $a)."<br>";
// $t = .800000000000000<br>

Upvotes: 3

Related Questions