代码之家  ›  专栏  ›  技术社区  ›  PlayHardGoPro

将字符串转换为相应的实体

  •  0
  • PlayHardGoPro  · 技术社区  · 6 年前

    所以我有一个annonymous函数,它将字符串中的每个字符转换为实体。

    var myStr = myStr.replace(/[\u0022\u0027\u0080-\FFFF]/g, function(a) {
       return '&#' + a.charCodeAt(0) + ';';
    });  
    

    我需要对PHP做同样的事情。
    我要一根普通的绳子 转换它的等效实体代码 .
    例如:

    有-->想要: Képzeld el PDF -------> Képzeld el PDF

    我在读关于 preg_replace_callback

    执行正则表达式搜索并使用回调替换

    但我不知道如何在PHP中应用相同的东西。
    我也可以在preg_replace中使用annonymous函数,如下所示:

     $line = preg_replace_callback(
            '/[\u0022\u0027\u0080-\FFFF]/g',
            function ($matches) {
                return '&#' + a.charCodeAt(0) + ';';
            },
        );
    

    我不能让它工作,也找不到 charCodeAt . 即使是regex范围的字符也不受支持 preg_replace 功能。

    1 回复  |  直到 6 年前
        1
  •  1
  •   revo shanwije    6 年前

    你可以用 IntlChar::ord() 找到一个字符的码位。以下是发声版本:

    $myStr = preg_replace_callback('~[\x{0022}\x{0027}\x{0080}-\x{ffff}]~u', function ($c) {
        return '&#' . IntlChar::ord($c[0]) . ';';
    }, $myStr);
    

    live demo