PHP 个特殊字符到 html 个实体代码

PHP special chars to html entity codes

我正在尝试将数组中的特殊字符转换为 html 实体代码:

这是我的助手数组:

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

这是函数:

    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;
    }

但是只有 returns 我这个数组,它转换了一些成功而一些没有:

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;"
]

你必须像这样使用 htmlentities 的第二个参数 "flag"

$htmlEntityArray = array_map(function($char) {
  return htmlentities($char, ENT_QUOTES | ENT_HTML5);
}, $specialChars);

您必须使用 ENT_QUOTESENT_HTML5 flags

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

var_export(array_map(function ($str) { return htmlentities($str, ENT_QUOTES | ENT_HTML5); }, $specialChars));

这个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;',
)

注意:我没有查看实体列表,因此没有注意到所有字符都有可用的翻译。我将留下答案,以防它可以帮助其他人使用不同的字符列表。


来自 docs(强调我的):

all characters which have HTML character entity equivalents are translated into these entities.

See Also

在其他情况下,使用 HTML-ENTITIES 作为目标编码,mb_convert_encoding() 可以获得更好的结果。问题在于您的实体中没有明显的模式(其中大多数是基本的 US-ASCII 字符,在 HTML 中没有任何特殊含义,因此不需要转换为 HTML 实体出于任何常见原因)。所以你有两个选择: