Code :
function preg_replace_except_inside_bbcode($pattern, $replacement, $subject, $temp_flag = '###~FOLDED~###') { // Capturing BBCode into an array $bbcode_capture_pattern = '#\[([^]]*)\].*\[/\\1\]#isU'; if (preg_match_all($bbcode_capture_pattern, $subject, $matches) == false) { return false; } if (count($matches) == 0) { return $subject; } $folded_entities = $matches[0]; // Folding BBCode inside initial text $folded_subject = preg_replace($bbcode_capture_pattern, $temp_flag, $subject); // Splitting subject into "outside of BBCode parts" $subject_parts = split($temp_flag, $folded_subject); // Applying requested replace + unfolding $subject = preg_replace($pattern, $replacement, $subject_parts[0]); for ($i = 1; $i < count($subject_parts); $i++ ) { $subject .= $folded_entities[$i - 1] . preg_replace($pattern, $replacement, $subject_parts[$i]); } return $subject; }
|