简体   繁体   English

如何在PHP中的这个字符串中使用动态整数分隔符分割一个字符串?

[英]How to split a string with dynamic integer delimiter inside this string in PHP?

Hex string looks like:十六进制字符串如下所示:

$hexString = "0307wordone0Banotherword0Dsomeotherword";

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

First byte ( 03 ) is total number of words in string.第一个字节 ( 03 ) 是字符串中的总字数。 Next byte is count for characters of the first word ( 07 ).下一个字节是第一个字 ( 07 ) 的字符计数。 And after 7 bytes there is another integer 0B which tells that next word length is 11 ( 0B ) characters, and so on...在 7 个字节之后,还有另一个整数0B表示下一个字长是 11 ( 0B ) 个字符,依此类推...

What should function for exploding such string to array look like?将此类字符串分解为数组的函数应该是什么样的? We know how many iterations there should be from $wordsCount .我们知道$wordsCount应该有多少次迭代。 I've tried different approaches but nothing seems to work.我尝试了不同的方法,但似乎没有任何效果。

This can be parsed with a simple for loop in O(n) .这可以用O(n) 中的简单for循环解析。 No need for some fancy (and slow) regex solutions.不需要一些花哨的(和缓慢的)正则表达式解决方案。

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

you can solve this by iterating a pointer on the string with a for loop.您可以通过使用 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM