十六进制字符串看起来像:
$hexString = "0307wordone0Banotherword0Dsomeotherword";
$wordsCount= hexdec(substr($hexString , 0, 2));
第一个字节(03
)是字符串中的单词总数。下一个字节是第一个字(07
)的字符计数。在7个字节之后,还有另一个整数0B
,它告诉下一个字长是11(0B
)个字符,依此类推…
将这样的字符串分解为数组的函数应该是什么样子的?我们知道$wordsCount
应该有多少次迭代。我尝试过不同的方法,但似乎都不起作用。
这可以通过O(n)中的简单for
循环进行解析。不需要一些花哨(和缓慢)的正则表达式解决方案。
$hexString = "0307wordone0Banotherword0Dsomeotherword";
$wordsCount = hexdec(substr($hexString, 0, 2));
$arr = [];
for ($i = 0, $pos = 2; $i < $wordsCount; $i++) {
$length = hexdec(substr($hexString, $pos, 2));
$arr[] = substr($hexString, $pos + 2, $length);
$pos += 2 + $length;
}
var_dump($arr);
您可以通过用for循环迭代字符串上的指针来解决此问题。
$hexString = "0307wordone0Banotherword0Dsomeotherword";
$wordsCount= hexdec(substr($hexString , 0, 2));
$pointer = 2;
for($i = 0; $i<$wordsCount;$i++)
{
$charCount =hexdec(substr($hexString , $pointer, 2 ));
$word = substr($hexString , $pointer + 2, $charCount);
$pointer = $pointer + $charCount + 2;
$words[] = $word;
}
print_r($words);