Convert special characters

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KeredDrahcir
    Contributor
    • Nov 2009
    • 426

    Convert special characters

    I'd like to be able to convert speical characters to the ASCII code. There is the option to convert a quote to &quote; but I'd need to convert it to &#34 . I need to be able to do this with any special character.
    An even better option would be to convert &quote; directly to &#34 . Is there a way to do either of these things?
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    You can use the ord function to convert a character into it's ASCII value, which you can use to construct the HTML entity.

    Consider this:
    [code=php]<?php
    header('content-type: text/plain; charset=utf8');

    $char = '"';

    $html = htmlentities($c har, ENT_QUOTES, 'UTF-8');
    $int = ord($char);
    $html_int = "&#{$int};" ;

    echo "Char: $char\n";
    echo "HTML: $html\n";
    echo "Int : $int\n";
    echo "Spec: $html_int\n";
    ?>[/code]

    Comment

    • kovik
      Recognized Expert Top Contributor
      • Jun 2007
      • 1044

      #3
      To convert the descriptive entity to the ASCII entity would require a translation from one to the other. You could do this by building an array of all characters with descriptive entities and their corresponding ASCII entity, and then make use of the strtr function.

      You could build the array dynamically by checking all characters whose htmlentities value is not the same as their character value from the chr function.

      However, HTML makes use of a much larger character set than ASCII for descriptive entities. If you do make it dynamically, consider outputting it in the same syntax as a PHP array and then saving that statically, as to avoid re-processing every time that you want to use these entities.

      Comment

      • KeredDrahcir
        Contributor
        • Nov 2009
        • 426

        #4
        Thanks guys. In the end I out togther an array and used that for the coversion but I may try your suggestion Atli since it should save a lot of space.

        Thanks.

        Comment

        Working...