L
L
Lavrov952020-05-01 15:19:36
PHP
Lavrov95, 2020-05-01 15:19:36

Regex how to leave 2 characters if there are more than 2 of them from each other?

Example

abababcdcdcdabab

output should be like this

ababcdcdcdabab

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valentyn, 2020-05-02
@rotarepmipoleved

I doubt. that one regular expression can do this.
I guess you need something like this:

$str = "abababcdcdcdabab";
        $parts = preg_split('/([a-z]{2})/u', $str, 0, PREG_SPLIT_DELIM_CAPTURE);
        $parts = array_values(array_filter($parts));

        $skip = 0;
        $result = '';
        foreach($parts as $id => $part) {
            $next = isset($parts[$id+1]) ? $parts[$id+1] : false;
            if ($part == $next) {
                ++$skip;
            }
            if ($skip == 2) {
                $skip = 0;
                continue;
            }
            $result .= $part;
        }
        echo $result;

The output will be: "ababcdcdabab".
There is another option:
$str = "abababababcdcdcdcdcdabab";
        $parts = preg_split('/([a-z]{2})/u', $str, 0, PREG_SPLIT_DELIM_CAPTURE);
        $parts = array_values(array_filter($parts));

        $skip = 0;
        $last = '';
        $result = '';
        foreach($parts as $id => $part) {
            $next = isset($parts[$id+1]) ? $parts[$id+1] : false;
            if ($part == $next) {
                ++$skip;
            } else {
                $skip = 0;
            }
            if ($skip >= 2) {
                continue;
            }
            $result .= $part;
        }
        echo $result;

Output: "ababcdcdabab"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question