2017-07-25 44 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"); 
相关问题