简体   繁体   中英

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.

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

you can solve this by iterating a pointer on the string with a for loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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