Instantly share code, notes, and snippets.

@davidnash davidnash/index.php
Created May 12, 2016

Embed
What would you like to do?
Pretty print fractions as HTML characters using PHP
//from post at http://davidnash.com.au/pretty-print-fractions-html-characters-using-php/
//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 multiply / 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 '¾';
}
else {
if( $f[1] == 8 ) {
if( $f[0] == 1 )
return '⅛'; // 1/8
else if( $f[0] == 3 )
return '⅜'; // 3/8
else if( $f[0] == 5 )
return '⅝'; // 5/8
else if( $f[0] == 7 )
return '⅞'; // 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment