Question

I have this code:

<?php echo $price; ?>

which gives me this result:

1,500.99

This code works like a charm to superscript the numbers after the dot:

$parts = explode('.', $price); 
echo "$parts[0].<sup>$parts[1]</sup>";

but if I have a price like this: 1,500.99€ it superscripts the € sign as well. Can this be stoped? Not to superscript it if it's not a number, or to superscript only 2 characters after the dot?

It doesn't need to be the same code, if you have something else, I'll give it a try.

Thanks

Was it helpful?

Solution

Regular expressions may be a little more flexible:

<?php
$price = "1,500.99";
$pattern = '/([\d,]+\.)(\d+)(.*)$/';
// ...or '/([\d\.]+,)(\d+)(.*)$/' if your currencies are 1.500,00

$formatted = preg_replace($pattern, '$1<sup>$2</sup>$3', $price);
// gives "1,500<sup>.99</sup>"

$price = "1,500.99€";

$formatted = preg_replace($pattern, '$1<sup>$2</sup>$3', $price);
// gives "1,500<sup>.99</sup>€"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top