1

I'm using imagettftext to create images of certain text characters. To do this, I need to convert an array of hexidecimal character codes to their HTML equivalents and I can't seem to find any functionality built-in to PHP to do this. What am I missing? (through searching, I came across this: PHP function imagettftext() and unicode, but it none of the answers seem to do what I need - some characters convert but most don't).

Here's the resulting HTML representation (in the browser)

 [characters] => Array
    (
        [33] => A
        [34] => B
        [35] => C
        [36] => D
        [37] => E
        [38] => F
        [39] => G
        [40] => H
        [41] => I
        [42] => J
        [43] => K
        [44] => L
    )

Which comes from this array (not capable of rendering in imagettftext):

 [characters] => Array
    (
        [33] => &#x41
        [34] => &#x42
        [35] => &#x43
        [36] => &#x44
        [37] => &#x45
        [38] => &#x46
        [39] => &#x47
        [40] => &#x48
        [41] => &#x49
        [42] => &#x4a
        [43] => &#x4b
        [44] => &#x4c
    )
Community
  • 1
  • 1
jpea
  • 3,114
  • 3
  • 26
  • 26
  • You could use [`html_entity_decode()`](http://php.net/html_entity_decode) if you had proper HTML escapes like `A` instead of just `A`, but a custom `preg_replace`(_callback) would work as well. – mario Oct 02 '12 at 14:19

2 Answers2

4

Based on a sample from the PHP manual, you could do this with a regex:

$newText = preg_replace('/&#x([a-f0-9]+)/mei', 'chr(0x\\1)', $oldText);

I'm not sure a raw html_entity_decode() would work in your case, as your array elements are missing the trailing ; -- a necessary part of these entities.

EDIT, July 2015:

In response to Ben's comment noting the /e modifier being deprecated, here's how to write this using preg_replace_callback() and an anonymous function:

$newText = preg_replace_callback(
    '/&#x([a-f0-9]+)/mi', 
    function ($m) {
        return chr(hexdec($m[1]));
    },
    $oldText
);
smitelli
  • 6,835
  • 3
  • 31
  • 53
0

Well, you obviously haven't search hard enough. html_entity_decode().

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308