Here's a (non-regex) recursive function which takes the input string by reference. It'll work with any tag as long as the closing tag is the same as the opening tag except for the "/":
function strip_tagged_part(&$str, $tag1)
{
$tag2 = substr($tag1, 0, 1) . '/' . substr($tag1, 1);
$len2 = strlen($tag2);
$pos1 = strpos($str, $tag1);
$pos2 = strpos($str, $tag2);
if (($pos1 !== false) && ($pos2 !== false)) {
$str = substr($str, 0, $pos1) . substr($str, $pos2 + $len2);
strip_tagged_part($str, $tag1);
}
}
$msg = '[private]blah[/private]String to be [private]blah[/private]stripped.';
$tag = '[private]';
strip_tagged_part($msg, $tag);
echo $msg;
EDIT:
Or, if you want to save the removed parts in an array:🆒
function strip_tagged_part(&$str, &$prvt, $tag1)
{
$tag2 = substr($tag1, 0, 1) . '/' . substr($tag1, 1);
$len1 = strlen($tag1);
$len2 = strlen($tag2);
$pos1 = strpos($str, $tag1);
$pos2 = strpos($str, $tag2);
if (($pos1 !== false) && ($pos2 !== false)) {
$prvt[] = substr($str, $pos1 + $len1, $pos2 - $pos1 - $len1);
$str = substr($str, 0, $pos1) . substr($str, $pos2 + $len2);
strip_tagged_part($str, $prvt, $tag1);
}
}
$msg = '[private]blah[/private]String to be [private]blah[/private]stripped.';
$tag = '[private]';
strip_tagged_part($msg, $tagged_part, $tag);
echo $msg . '<br />';
foreach ($tagged_part as $value) {
echo $value . '<br />';
}