How to make the decimals superscript, or subscript, in PHP?

11,492

Solution 1

This is currently untested, but I think that's as simple as:

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

References:

Solution 2

You can use html sub and sup tags: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_sup

An example code could be:

echo preg_replace('/\.([0-9]*)/', '<sup>.$1</sup>', $price);
Share:
11,492
Nikola Nastevski
Author by

Nikola Nastevski

Updated on June 04, 2022

Comments

  • Nikola Nastevski
    Nikola Nastevski about 2 years

    I have this code:

    <?php echo $price; ?>
    

    which gives me this result:

    1,500.99
    

    Is there any way I can make the decimals superscript or subscript?

    Thanks.

    EDIT: This code works like a charm (thanks to David Thomas):

    $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? To not superscript it if it's not a number, or to superscript only 2 characters after the dot?

    • Matt Ball
      Matt Ball about 12 years
      Yes, there is. Use CSS. Do some research.
    • Sikshya Maharjan
      Sikshya Maharjan about 12 years
      Yes, but following the question suggests that the OP first needs to retrieve the numbers following the decimal point and then wrap those numbers in the relevant HTML tag. The question might be relatively simple, but I don't think it's worthy of a close-vote since there is, at least, a valid question being asked.
  • Nikola Nastevski
    Nikola Nastevski about 12 years
    Just a quick one :) If I have a price like this: 1,500.99€ it superscripts the € sign as well. Can this be stoped? To not superscript it if it's not a number, or to superscript only 2 characters after the dot?
  • Sikshya Maharjan
    Sikshya Maharjan about 12 years
    Yeah, it's possible; but in that case you'll be looking at regex solutions and while I'm okay with JavaScript regex, php still manages to confuse me, some.
  • Nikola Nastevski
    Nikola Nastevski about 12 years
    So, no quick fix to your code? Ok, I'll try to search for it ;) Thanks for everything, you've been very helpful. Your code is very simple, yet effective, thanks again.
  • Nikola Nastevski
    Nikola Nastevski about 12 years
    No luck. I edited my initial question, so hopefully someone will make a fix for it.
  • Sikshya Maharjan
    Sikshya Maharjan about 12 years
    Post a different question, don't just edit to add more and more. Particularly since the question you initially asked has been answered. Also, first do a search on the site to see if you can find any PHP questions and answers that might be relevant.
  • Nikola Nastevski
    Nikola Nastevski about 12 years
    Ok, I'll do what you've suggested, thanks a lot ;) I always search first, but sometimes I just can't find and/or figure it out how to do it :) Take care buddy.