0

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

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

Thanks

3
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by farhan386
0

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.

2
<?php
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

11xxxxx1100010011xxxxx1
11xxxxx1111111111xxxxx1
11000001111111111000001
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.