Search code examples
phpspecial-charactershtml-entitiesarray-map

PHP special chars to html entity codes


I am trying to convert the special chars in my array to html entity codes:

this is my helper array:

'specialChars' => [
    '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+',
    ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\',
    ']', '^', '_', '`', '{', '|', '}', '§', '©', '¶'
]

And this is the function:

    public static function convert($specialChars = [])
    {
        $htmlEntityArray = [];

        if(count($specialChars) == 0)
        {
            $specialChars = Config::get('constants.specialChars'); // gets the special char from the helper array
        }

        foreach ($specialChars as $key => $value)
        {
            $htmlEntityArray = array_map("htmlentities", $specialChars);
        }

        return $htmlEntityArray;
    }

But that only returns me this array, it convert some successfully and some not:

array:32 [▼
  0 => "!"
  1 => "&quot;"
  2 => "#"
  3 => "$"
  4 => "%"
  5 => "&amp;"
  6 => "'"
  7 => "("
  8 => ")"
  9 => "*"
  10 => "+"
  11 => ","
  12 => "/"
  13 => ":"
  14 => ";"
  15 => "&lt;"
  16 => "="
  17 => "&gt;"
  18 => "?"
  19 => "@"
  20 => "["
  21 => "\"
  22 => "]"
  23 => "^"
  24 => "_"
  25 => "`"
  26 => "{"
  27 => "|"
  28 => "}"
  29 => "&sect;"
  30 => "&copy;"
  31 => "&para;"
]

Solution

  • You have to use the ENT_QUOTES and ENT_HTML5 flags.

    $specialChars = [
        '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+',
        ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\',
        ']', '^', '_', '`', '{', '|', '}', '§', '©', '¶'
    ];
    
    var_export(array_map(function ($str) { return htmlentities($str, ENT_QUOTES | ENT_HTML5); }, $specialChars));
    

    This returns:

    array (
        0 => '&excl;',
        1 => '&quot;',
        2 => '&num;',
        3 => '&dollar;',
        4 => '&percnt;',
        5 => '&amp;',
        6 => '&apos;',
        7 => '&lpar;',
        8 => '&rpar;',
        9 => '&ast;',
        10 => '&plus;',
        11 => '&comma;',
        12 => '&sol;',
        13 => '&colon;',
        14 => '&semi;',
        15 => '&lt;',
        16 => '&equals;',
        17 => '&gt;',
        18 => '&quest;',
        19 => '&commat;',
        20 => '&lbrack;',
        21 => '&bsol;',
        22 => '&rsqb;',
        23 => '&Hat;',
        24 => '&lowbar;',
        25 => '&grave;',
        26 => '&lbrace;',
        27 => '&vert;',
        28 => '&rcub;',
        29 => '&sect;',
        30 => '&copy;',
        31 => '&para;',
    )