0

I am having an array

$array = array("ab","aab","abb","abab","abaab","abbb");

I want to search the elements that contain duplicate consecutive characters like aab, abb, abbb and replace them with 1.

Conversely, if an element does not contain any duplicate consecutive characters, (like ab and abab) then it should be replaced with 0.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

1

This approach uses array_map and preg_match to return an array of true/false matches based on a repeating string. The keys will match your input array.

(.) finds any character and puts it into the first capturing group, then \1 makes sure the exact matching character follows it.

$array = array("ab","aab","abb","abab","abaab","abbb");
function StringHasRepetition( $string )
{
  return preg_match('/(.)\1/', $string);
}
$matches = array_map('StringHasRepetition',$array);
print_r( $matches );
// Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 0 [4] => 1 [5] => 1 ) 

As a Lambda function:

$array = array("ab","aab","abb","abab","abaab","abbb");
$matches = array_map( function( $string ){
  return preg_match('/(.)\1/', $string);
} ,$array);
print_r( $matches );
// Array ( [0] => 0 [1] => 1 [2] => 1 [3] => 0 [4] => 1 [5] => 1 )
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
1

preg_replace() can manipulate your entire array with just two regex patterns in a single call. First convert strings with no consecutive repeated characters to 0. Then convert all non 0 values to 1.

Code: (See Demo Link for a more verbose breakdown of the method)

$array=["ab","aab","abb","abab","abaab","abbb",'1','11','10','0','00100','1101','01'];
var_export(preg_replace(['/^(?:(.)(?!\1))*$/','/^(?!0$).*/'],[0,1],$array));

Output:

array (
  0 => '0',
  1 => '1',
  2 => '1',
  3 => '0',
  4 => '1',
  5 => '1',
  6 => '0',
  7 => '1',
  8 => '0',
  9 => '0',
  10 => '1',
  11 => '1',
  12 => '0',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136