- preg_replace_callback: documentation ( source)
- preg_replace: documentation ( source)
<?php
$regex = <<<'REGEX'
~
<strong\s*> # Match strong open tag
( # Open group 1
(?: # Non-capturing group
(?:(?!</?strong\s*>).) # Match anything that's not strong tag (open/close)
| # Or
(?R) # Repeat the whole pattern
)* # Repeat the non-capturing group zero or more times
) # Close group 1
</strong\s*> # Match strong close tag
~xs
REGEX;
# The x modifier is for the fancy spacing en commenting
# The s modifier is to match newlines with dot "."
$output = preg_replace_callback($regex, function($m){
return '<strong>' . preg_replace('~</?strong\s*>~', '', $m[1]) . '</strong>';
}, $input);
echo $output; // w1 <strong>w2</strong> w3 w4 <strong>w5 w6</strong> w7