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

Dani AI

Generated

A clean one-pass approach is to use preg_replace_callback so each matched run of zeros is inspected and the replacement is produced dynamically. This follows 's suggestion and achieves the same goal as 's multi-pass/placeholder trick but without the temporary markers.

<?php
$threshold = 5;

$result = preg_replace_callback('/0+/', function($m) use ($threshold) {
    $len = strlen($m[0]);
    return ($len < $threshold) ? str_repeat('1', $len) : $m[0];
}, $string);

For environments where anonymous functions are not available (older PHP versions), an equivalent named-function version works the same way:

<?php
function replace_short_zero_runs($matches) {
    $len = strlen($matches[0]);
    return ($len < 5) ? str_repeat('1', $len) : $matches[0];
}

$result = preg_replace_callback('/0+/', 'replace_short_zero_runs', $string);

Notes and cautions: the pattern /0+/ matches any contiguous zero-run; the callback checks its length and returns either a same-length string of 1 characters or the original match to preserve long runs. Use strlen for ASCII binary strings; use mb_strlen only if the input contains multibyte characters. Anonymous functions require PHP 5.3+. 's placeholder method is still a valid fallback when callbacks are inconvenient, but the callback approach is simpler and easier to maintain.

Recommended Answers

All 3 Replies

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.

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

Thanks d5e5, it works like a charm

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.