获取字符串中第一个字符的重复值

时间:2017-07-25 14:47:18

标签: php strpos

我有一个类似于这个的字符串,

$string = "01110111011101110111101110111110111111";

我需要获取字符串中的第一个字符(在本例中为0)。然后我需要获取字符串中所有出现的字符的位置。所有出现的事件都应放入一个数组中,第一个元素为1(第一个出现的是字符串的第一个字符)。

例如,上面的字符串应该生成这样的数组,

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

3 个答案:

答案 0 :(得分: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 :(得分: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) }

答案 2 :(得分: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");