Search code examples
phpstringexplode

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.


Solution

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