2014-09-11 92 views
2

十六進制字符串的樣子:如何在PHP中的這個字符串中使用動態整數分隔符分割字符串?

$hexString = "0307wordone0Banotherword0Dsomeotherword"; 

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

第一個字節字符串總字數。下一個字節是第一個字的字符數(7)。並且在7個字節之後還有另一個整數0B,它告訴下一個字長是11(0B)個字符,等等......

這個字符串到數組的爆炸應該是什麼樣子?我們知道$ wordsCount應該有多少個循環。我嘗試了不同的方法,但似乎沒有任何工作。

+0

使用實際整數可能更高效。有了這個,你的字數限制爲255,而你可以支持16位整數的字數/字符數。 – Flosculus 2014-09-11 10:32:33

+0

@Flosculus - 我確信每個單詞都比8bit短。 – Leszek 2014-09-11 10:36:01

回答

3

這可以使用簡單的for循環在O(n)中解析。無需一些花哨的(和緩慢的)正則表達式解決方案。

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

這是工作。我只需要更改$ lenght * 2,因爲我沒有提到單詞是十六進制的ASCII值。謝謝你,先生! – Leszek 2014-09-11 11:21:00

0

你可以通過迭代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); 
相關問題