2017-07-25 89 views
0

我有類似下面這樣的字符串,得到第一個字符的重複值的字符串

$string = "01110111011101110111101110111110111111"; 

我需要得到的字符串中的第一個字符(在這種情況下,0)。然後我需要得到字符串中該字符出現的位置。所有的出現都應該放入第一個元素爲1的數組中(第一個出現的是字符串的第一個字符)。

例如,上面的字符串應該產生這樣的陣列,

$return_value = array([0]=>1, [1]=>5, [2]=>9, [3]=>13, [4]=> 17....); 
+1

請說清楚。我無法理解你的問題。 –

+0

感謝您的回覆 我如何獲得重複字符的第一個和最後一個位置 $ string =「011101110111」; 輸出如: $ first_position_values = array([0] => 1,[1] => 5,[3] => 9); $ last_position_values = array([0] => 3,[1] => 7,[3] => 11); –

回答

0

這應該可以解決問題,

$string = "01110111011101110111101110111110111111"; 
$offset = 0; 
$return_value = array(); 
$character = substr($string, 0, 1); 

while (($offset = strpos($string, $character, $offset))!== false) { 
    $return_value[] = $offset + 1; 
    $offset = $offset + strlen($character); 
} 

var_dump($return_value); 

哪個RETURN_VALUE會產生,

array(8) { [0]=> int(1) [1]=> int(5) [2]=> int(9) [3]=> int(13) [4]=> int(17) [5]=> int(22) [6]=> int(26) [7]=> int(32)} 
+1

@Odyssey - 謝謝你sir –

+0

@PHP沒問題,請把它標記爲選定的答案(https://i.imgur.com/NqBB71W.png),謝謝! – Tom

0

這裏是我的答案,我希望它能幫助你。

$string = "01110111011101110111101110111110111111"; 
$return_value = array(); 
$select = 0;      //Select value you want to find 
for($i = 0; $i < strlen($string); $i++) 
{ 
    if($string[$i] == $select) $return_value[] = $i + 1; //Get the position in string 
} 
var_dump($return_value); 

Result 
array(8) { [0]=> int(1) [1]=> int(5) [2]=> int(9) [3]=> int(13) [4]=> int(17) [5]=> int(22) [6]=> int(26) [7]=> int(32) } 
0

一個簡單的解決方案:將字符串拆分爲字符,然後遍歷列表並在當前字符更改時進行註冊。

當它從0更改爲1這是一個開始:記住當前位置;當它從1變爲0時,它結束了:請記住上一個位置(最後一個1的位置)。

$string = "01110111011101110111101110111110111111"; 

// The current character 
// Used also as index in $positions (0 => starts, 1 => ends) 
// And also used to adjust the stored position: 
// ends are 1 character less that the current position 
$current = '0'; 
// Collect starts and ends here ([0] => starts, [1] => ends) 
$positions = array(array(), array()); 
// The current position in string; start before the first character 
$pos = -1; 
// Split the string to characters 
foreach (str_split($string) as $digit) { 
    // Advance to the current position in string 
    $pos ++; 
    // When the current character changes... 
    if ($digit != $current) { 
     // ... put the position in the appropriate list 
     $positions[$current][] = $pos - $current; 
    } 
    // Update current character 
    $current = $digit; 
} 
// If the last digit was a '1' then it is an (unrecorded) end 
if ($current == '1') { 
    // There is no need to adjust, $pos is strlen($string)-1 
    $positions[$current][] = $pos; 
} 

// Dump the result 
echo("start: ". implode(', ', $positions[0])."\n"); 
echo("end : ". implode(', ', $positions[1])."\n"); 
相關問題