How to split a string into duplicate characters in PHP?

I am trying to split a binary string into an array of duplicate characters.

For example, an array 10001101divided by this function would be:

    $arr[0] = '1';
    $arr[1] = '000';
    $arr[2] = '11';
    $arr[3] = '0';
    $arr[4] = '1';

(I tried to understand, but if you still do not understand, my question is the same as this one , but for PHP, not Python)

+4
source share
3 answers

You can use preg_splitlike this:

Example:

$in = "10001101";
$out = preg_split('/(.)(?!\1|$)\K/', $in);

print_r($out);

Output:

Array
(
    [0] => 1
    [1] => 000
    [2] => 11
    [3] => 0
    [4] => 1
)

Regular expression:

  • (.) - match one character and fix it
  • (?!\1|$) - look at the next position and compare if it does not match the one we just found and not the end of the line.
  • \K - , , .

. PHP 5.6.13, \K.


, , :

$out = preg_split('/(?<=(.))(?!\1|$)/', $in);

lookbehind , \K, .

+3
<?php
$s = '10001101';
preg_match_all('/((.)\2*)/',$s,$m);
print_r($m[0]);
/*
Array
(
    [0] => 1
    [1] => 000
    [2] => 11
    [3] => 0
    [4] => 1
)
*/
?>

1 . ((.), $m[1]), (((.)\2*), $m[0]). preg_match_all . , . 'aabbccddee'. 0 1, [01] . .

, $m , , , .. isset($m[0]), .

+1

. , , , .

$chunks = array();
$index = 0;
$chunks[$index] = $arr[0];
for($i = 1; $i < sizeof($arr) - 1; $i++) {
  if( $arr[$i] == $arr[$i-1] ) {
    $chunks[$index] .= $arr[$i];
  } else {
    $index++;
    $chunks[$index] = $arr[$i];
  }
}
0

Source: https://habr.com/ru/post/1612120/


All Articles