I have a string contains sequences of 0 and 1. I need to replace all zero sequences whose length less than 5, into number 1 with same length. The zero sequences with length 5 or more should be left as is.

For example

source : 11000001100010011000001
result : 11000001111111111000001

$string = '11111000011100000110010';
$pattern = '/0{1,4}/i';
$replacement = '1'; // what should I put here?
echo preg_replace($pattern, $replacement, $string);


Not sure that is possible in one go. I think you can use preg_replace_callback. Search for all 0 parts, and use the callback to determine their length and return either the same value (>= 5) or a replacement with 1's.

function string_of_xes($matches)
  // as usual: $matches[0] is the complete match
  $r = str_repeat('x', strlen($matches[0]));
  return $r;

$pattern = '/0{5,}/';
$string = '11000001100010011000001';
//Replace all strings of 0's with length 5 or longer with same # of x's
$temp1 = preg_replace_callback($pattern, string_of_xes, $string);
echo $temp1 . "\n";

//Replace all remaining 0's with 1's
$pattern = '/0/';
$temp2 = preg_replace($pattern, '1', $temp1);
echo $temp2 . "\n";

//Restore the x's back to 0's
$pattern = '/x/';
$string_out = preg_replace($pattern, '0', $temp2);
echo $string_out;

Output is


Thanks d5e5, it works like a charm