需要帮助将ruby函数移植到php

时间:2011-06-04 00:42:03

标签: php ruby string encoding

我有这个红宝石功能:

def WhitespaceHexEncode(str)
    result = ""
    whitespace = ""
    str.each_byte do |b|
        result << whitespace << "%02x" % b
        whitespace = " " * (rand(3) + 1)
    end
    result
end

我试图在php上做同样的事情,这是我到目前为止的代码:

function WhitespaceHexEncode($str)
{
    $result = "";
    $whitespace = "";
    for($i=0;$i<strlen($str);$i++)
    {
        $result = $result.$whitespace.sprintf("%02x", $str[$i]);
        $whitespace = " ";
        for($x=0;$x<rand(0,5);$x++)
            $whitespace = $whitespace." ";
    }
    return $result;
}

但是PHP函数没有显示与ruby相同的输出,例如:

print WhitespaceHexEncode("test fsdf dgksdkljfsd sdfjksdfsl")

Output: 74   65 73 74   20 66  73   64   66  20   64 67   6b  73   64  6b 6c 6a  66   73 64   20 73 64   66 6a   6b  73   64   66 73   6c

--------------------------------------------------------------

echo WhitespaceHexEncode("test fsdf dgksdkljfsd sdfjksdfsl")

Output: 00 00  00    00   00  00 00  00  00 00   00    00 00    00 00   00  00   00     00  00  00   00 00    00   00 00 00   00   00   00  00   00

有人能告诉我php代码有什么问题吗?


更新:使用bin2hex()

修复了它

1 个答案:

答案 0 :(得分:1)

以下内容也应该有效:

<?php

function WhitespaceHexEncode($str) {

    $result = '';
    foreach (str_split($str) as $b) {
        $bytes      = $whitespace = sprintf('%02x', ord($b));
        $whitespace = str_repeat(' ', (rand(0, 5) + 1));
        $result    .= $bytes . $whitespace;
    }

    return $result;
}

echo WhitespaceHexEncode('test fsdf dgksdkljfsd sdfjksdfsl');
相关问题