[英]How to split a string with dynamic integer delimiter inside this string in PHP?
十六進制字符串如下所示:
$hexString = "0307wordone0Banotherword0Dsomeotherword";
$wordsCount= hexdec(substr($hexString , 0, 2));
第一個字節 ( 03
) 是字符串中的總字數。 下一個字節是第一個字 ( 07
) 的字符計數。 在 7 個字節之后,還有另一個整數0B
表示下一個字長是 11 ( 0B
) 個字符,依此類推...
將此類字符串分解為數組的函數應該是什么樣的? 我們知道$wordsCount
應該有多少次迭代。 我嘗試了不同的方法,但似乎沒有任何效果。
這可以用O(n) 中的簡單for
循環解析。 不需要一些花哨的(和緩慢的)正則表達式解決方案。
$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);
您可以通過使用 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.