简体   繁体   English

PHP:字符串到完整ASCII

[英]PHP: String to full ASCII

I'm using an RTF converter and I need 240 as &#U050&#U052&#U048 but Im not to sure how to do this!?! 我使用的是RTF转换器,我需要240作为&#U050&#U052&#U048但是我不确定如何做到这一点!

I have tried using the following function: 我尝试使用以下功能:

function string_to_ascii($string) {
    $ascii = NULL;
    for ($i = 0; $i < strlen($string); $i++) {
            $ascii += "&#U"+str_pad(ord($string[$i]),3,"0",STR_PAD_LEFT);
    }
    return($ascii);
}

But it still just outputs just the number (eg 2 = 50 ) and ord just makes it go mad. 但是它仍然只输出数字(例如2 = 50 ),而ord只会使它发疯。

I've tried echo "-&#U"+ord("2")+"-"; 我试过了echo "-&#U"+ord("2")+"-"; and I get 50416 !?!? 我得到50416 !?!?

I have a feeling it might have something to do with encoding 我觉得它可能与编码有关

I think you're over thinking this. 我认为您已经考虑过了。 Convert the string to an array with str_split , map ord to all of it, then if you want to format each one, use sprintf (or str_pad if you'd like), like this: 字符串转换为与阵列str_split地图 ord所有的话,那么如果你想每一个,使用格式化sprintf (或str_pad如果你喜欢),就像这样:

function string_to_ascii($string) {
    $array = array_map( 'ord', str_split( $string));
    // Optional formatting:
    foreach( $array as $k => &$v) {
        $v = sprintf( "%03d", $v);
    }
    return "&#U" . implode( "&#U", $array);
}

Now, when you pass string_to_ascii( '240') , you get back string(18) "&#U050&#U052&#U048" . 现在,当您传递string_to_ascii( '240') ,您将返回string(18) "&#U050&#U052&#U048"

Just found this: 刚发现这个:

function to_ascii($string) {
    $ascii_string = '';
    foreach (str_split($string) as $char) {
        $ascii_string .= '&#' . ord($char) . ';';
    }
    return $ascii_string;
}

here 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM