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?
6 Answers
Reset to default 8Try 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
String.charCodeAt
and now you're asking for the reverse? – Alvin Wong Commented Oct 20, 2012 at 16:06String.fromCharCode
is basically UTF-16 – Alvin Wong Commented Oct 20, 2012 at 16:10IntlChar::chr(31337)
– Lime Commented Jul 15, 2017 at 20:30