在PHP中如何使用动态整数分隔符拆分字符串?

3

十六进制字符串看起来像:

$hexString = "0307wordone0Banotherword0Dsomeotherword";

$wordsCount= hexdec(substr($hexString , 0, 2));

首字节(03)是字符串中单词的总数。下一个字节是第一个单词的字符计数(07)。在7个字节之后,有另一个整数0B,它告诉下一个单词的长度是11(0B)个字符,以此类推...

如何实现将这样的字符串转换为数组的函数?我们知道迭代次数应该从$wordsCount中得到。我尝试了不同的方法,但似乎没有什么作用。


使用实际整数可能更有效率。这样,您的字限制为255,而您可以支持16位整数的单词/字符计数。 - Flosculus
@Flosculus - 我确信每个单词都不超过8位。 - Leszek
2个回答

3
这可以通过简单的 for 循环在 O(n) 的时间复杂度内解析。不需要使用一些花哨(且缓慢)的正则表达式解决方案。
$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);

这个可以工作。我只需要改变 $length*2,因为我没有提到单词是十六进制的ASCII值。谢谢您! - Leszek

0
你可以通过使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接