8

We've got some fraction information stored in the database, e.g. ¾ ½

Short of doing a search and replace, are there any inbuilt PHP functions that will automatically convert these to proper html entities?

Tom
  • 33,626
  • 31
  • 85
  • 109

4 Answers4

3

You can use the htmlentities() function. This will replace all special characters with their HTML equivalent. It should do the job.

Sam Becker
  • 19,231
  • 14
  • 60
  • 80
3

htmlentities.

But you probably don't need to. Serve your page in an encoding that includes them (UTF-8, ISO-8859-1) and you can include those as literal, unescaped characters.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • really? does this just apply to fractions? – Tom Apr 07 '09 at 10:18
  • 1
    Utf-8 will allow you to use almost any character without conversion. You should still call htmlentities for security, though. http://akrabat.com/2009/03/18/utf8-php-and-mysql/ details the steps to use UTF-8 - you need to make changes to php, mysql and html. – David Snabel-Caunt Apr 07 '09 at 11:05
  • It applies to anything you can fit in the encoding you're using. If you're in ISO-8859-1 (Western European) you get up to U+00FF, which includes ¼½¾ (U+00BC-U+00BE). If you're using UTF-8, that includes the whole Unicode character gamut. Though you'd still need htmlspecialchars to deal with ‘<’/‘&’. – bobince Apr 07 '09 at 11:07
1

The answer is already given: use htmlentities(). In addition, the use of UTF-8 has been suggested, which of course is a really good idea. However, if you're planning on using htmlentities() on UTF-8 strings, use the following code (or you'll get weirdly encoded characters):

htmlentities($str, ENT_COMPAT, 'UTF-8')

As you can imagine, it sucks having to add the second and third argument all the time. For most projects I need htmlentities() in, I end up writing the a shortcut function, i.e.:

function he($str) { // shortcut function for htmlentities() with UTF-8 settings
 return htmlentities($str, ENT_COMPAT, 'UTF-8');
}
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
0

try htmlentities()

Shard
  • 3,175
  • 6
  • 30
  • 40