doujia1163 2018-05-23 17:49
浏览 83
已采纳

将字符串转换为它的对应实体

So I have this annonymous function that converts every character of my string into entity.

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

I need to do the same with PHP.
I'll have a normal string and transform it it's equivalent entity code.
e.g:

Have --> Want: Képzeld el PDF ------->Képzeld el PDF

I was reading about preg_replace_callback

Perform a regular expression search and replace using a callback

But I don't know how to apply the same thing in PHP.
I could also use the annonymous function within preg_replace, like so:

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

I couldn't make it work or find an equivalence for charCodeAt. Even the regex range of characters are not supported by preg_replace function.

  • 写回答

1条回答 默认 最新

  • dsedug8644 2018-05-23 20:23
    关注

    You could use IntlChar::ord() to find the codepoint of a character. Below is a transpiled version:

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

    See live demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 三菱FX系列PLC串口指令
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型