Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Next byte is count for characters of the first word (07). And after 7 bytes there is another integer 0B which tells that next word length is 11 (0B) characters, and so on...

What should function for exploding such string to array look like? We know how many iterations there should be from $wordsCount. I've tried different approaches but nothing seems to work.

like image 623
Leszek Avatar asked Sep 11 '26 04:09

Leszek


1 Answers

This can be parsed with a simple for loop in O(n). 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);
like image 200
Ke Vin Avatar answered Sep 13 '26 17:09

Ke Vin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!