Skip to content
PHP Logo

How can one effectively replace characters outside of specific BBCode tags using preg_replace in PHP?

To effectively replace characters outside of specific BBCode tags using preg_replace in PHP, you can use a regular expression to match the text outside the tags and then apply the replacement. You can achieve this by using a combination of preg_replace and regex patterns to target the text outside the BBCode tags.

php
// Sample input string with BBCode tags
$input = "[b]Hello[/b] [i]World[/i]";

// Define the regex pattern to match text outside BBCode tags
$pattern = '/\[\/?[^\]]*\]/';

// Replace characters outside BBCode tags with a specific string
$output = preg_replace($pattern, '', $input);

echo $output; // Output: Hello World