2011-06-04 124 views
0

我有这种红宝石功能:需要帮助移植红宝石功能到PHP

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函数不显示输出相同红宝石之一,例如:

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代码?


UPDATE:固定它使用BIN2HEX()

+0

是什么做| B |手段? – dynamic 2011-06-04 00:44:39

+0

@ yes123来自ruby,b拥有each_byte迭代器的每个字符。在这种情况下,b是来自“str”参数的字符串中的每个字符。 – fitkax 2011-06-04 00:46:02

+0

它就像一个嵌套的?从来没有看到这样的误导性语法 – dynamic 2011-06-04 00:58:50

回答

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