簡體   English   中英

需要幫助將 ruby function 移植到 php

[英]Need help porting ruby function to php

我有這個 ruby function:

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 function 沒有顯示相同的 output 與 Z58E53D13208995EDB9 例如:

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() 修復它

以下也應該起作用:

<?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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM