最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript function in PHP fromCharCode() - Stack Overflow

programmeradmin4浏览0评论
var test = String.fromCharCode(112, 108, 97, 105, 110);
document.write(test);

// Output: plain

Is there any PHP Code to work as String.fromCharCode() of javascript?

var test = String.fromCharCode(112, 108, 97, 105, 110);
document.write(test);

// Output: plain

Is there any PHP Code to work as String.fromCharCode() of javascript?

Share Improve this question asked Oct 20, 2012 at 16:01 LIGHTLIGHT 5,71211 gold badges38 silver badges79 bronze badges 4
  • blog.stanislavstankov.com/2010/02/… – Leniel Maccaferri Commented Oct 20, 2012 at 16:06
  • 2 You first asked String.charCodeAt and now you're asking for the reverse? – Alvin Wong Commented Oct 20, 2012 at 16:06
  • This is what you want, because String.fromCharCode is basically UTF-16 – Alvin Wong Commented Oct 20, 2012 at 16:10
  • 1 This works better then the posted answers IntlChar::chr(31337) – Lime Commented Jul 15, 2017 at 20:30
Add a comment  | 

6 Answers 6

Reset to default 8

Try the chr() function:

Returns a one-character string containing the character specified by ascii.

http://php.net/manual/en/function.chr.php

PHP has chr function which would return one-character string containing the character specified by ascii

To fit your java script style you can create your own class

$string = String::fromCharCode(112, 108, 97, 105, 110);
print($string);

Class Used

class String {
    public static function fromCharCode() {
        return array_reduce(func_get_args(),function($a,$b){$a.=chr($b);return $a;});
    }
}

Try something like this..

 // usage: echo fromCharCode(72, 69, 76, 76, 79)
    function fromCharCode(){
      $output = '';
      $chars = func_get_args();
      foreach($chars as $char){
        $output .= chr((int) $char);
      }
      return $output;
    } 

The live demo.

$output = implode(array_map('chr', array(112, 108, 97, 105, 110)));

And you could make a function:

function str_fromcharcode() {
    return implode(array_map('chr', func_get_args()));
}

// usage
$output = str_fromcharcode(112, 108, 97, 105, 110);

The chr() function does this, however it only takes one character at a time. Since I'm not aware of how to allow a variable number of arguments in PHP, I can only suggest this:

function chrs($codes) {
    $ret = "";
    foreach($codes as $c) $ret .= chr($c);
    return $ret;
}
// to call:
chrs(Array(112,108,97,105,110));

Use chr() if you only need ASCII support.

echo chr(120); // outputs "x"

Or its multi-byte twin mb_chr() if you need Unicode (requires mbstring extension):

echo mb_chr(23416); // outputs "學" 

See:

  • http://php.net/manual/en/function.chr.php
  • https://www.php.net/manual/en/function.mb-chr.php
发布评论

评论列表(0)

  1. 暂无评论