3v4l.org

run code in 300+ PHP versions simultaneously
<?php $string = 'xxx bla *xxx bla bla **xxx bla bla ***xxx bla bla ****xxx'; $search = 'xxx'; $char = '*'; $string = preg_replace_callback( '/\b(' . preg_quote($char) . '*)(' . $search . ')\b/', function($matches) { global $char; if(strlen($matches[1]) % 2 === 0) { return $matches[1] . $char . $matches[2]; } else { return $matches[0]; } }, $string ); print $string;

preferences:
60.22 ms | 402 KiB | 5 Q