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:

//supply a string, eg 1/2, return eg ½
function str_to_fraction( $str ) {
	$f = explode('/', $str);

	if( count($f) != 2 ) {
		return $str; //if there's multiple '/' chars, this isn't a fraction
	}
	else {
		//return single html entities where they exist
		if( $f[0] == 1 && ( $f[1] == 2 || $f[1] == 4 ) ) {
			// 1/2, 1/4
			return '&frac1'.$f[1].';';
		}
		else if( $f[0] == 3 && $f[1] == 4 ) {
			// 3/4
			return '&frac34;';
		}
		else {
			if( $f[1] == 8 ) {
				if( $f[0] == 1 )
					return '&#8539;'; // 1/8
				else if( $f[0] == 3 )
					return '&#8540;'; // 3/8
				else if( $f[0] == 5 )
					return '&#8541;'; // 5/8
				else if( $f[0] == 7 )
					return '&#8542;'; // 7/8
			}

			//else it's a 'crazy' fraction, but we can handle that:
			return "<sup>$f[0]</sup>&frasl;<sub>$f[1]</sub>";
		}

	} //end if a string of form X/Y

} //str_to_fraction()

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 *