Search code examples
phpunicodefractions

What is the easiest way to parse a string and replace 1/2 with ½ (and similar) in PHP?


I have a string with many fractions like 1/2, 1/4 etc. I want to replace them with their Unicode equivalents.

I realise I could pick them up with

/\s(\d+)\/(\d+)\s/

How would I replace them with their Unicode equivalents? I could probably wrap the numbers in span and do something similar with CSS, but I was wondering if there was an easy way to convert them.

Do I need to have a 1:1 mapping of regex to Unicode character?


Solution

  • Given that there's only a few of them, you could just create a mapping like so:

    $fractions = array(
        '1/4' => '¼', '1/3' => '⅓',
        '3/8' => '⅜', ...
      );
    

    I'd say that's probably the easiest way... kind in mind that many people won't have fonts installed that can display all of them anyway.