Pretty print fractions as HTML entities using PHP

David Nash code, html, php 1 Comment

I used this code in a WordPress site but it’s pure HTML.

I wanted to take a string, for example “3/4” and convert it to a HTML entity ¾.

When there’s no HTML entity I still wanted it to look nice, using <sup> and <sub> for the numerator and denominator respectively.

I couldn’t find anything on the web that I could copy and paste so I wrote it myself. Here’s what I came up with:

It’s pretty straight forward. First we check that the string is of the form X/Y. We put the X and Y into an array, and then use those elements to find a nice HTML entity that matches. If we can’t, we use <sup> and <sub> elements, for example 427.

I’ve also created a gist of this here: https://gist.github.com/davidnash/304d708789f7d84e5161c20555e9bc18

I hope this saves you a little time – when you’re working on deadline, every minute counts!

Comments 1

  1. Pingback: Link WP Ultimate Recipe ingredients to WooCommerce products - David Nash

Leave a Reply

Your email address will not be published. Required fields are marked *