What are best practices for replacing content within custom tags using preg_replace in PHP?

When using preg_replace in PHP to replace content within custom tags, it is important to use capturing groups in the regular expression pattern to extract the content within the tags. This allows you to easily replace the content while preserving the custom tags themselves. Additionally, using the /e modifier in preg_replace allows you to evaluate the replacement string as PHP code, enabling dynamic content replacement within the custom tags.

$content = "This is some [custom]sample content[/custom] with custom tags.";

// Define the regular expression pattern with capturing groups
$pattern = '/\[custom\](.*?)\[\/custom\]/e';

// Replace the content within the custom tags with dynamic content
$new_content = preg_replace($pattern, "'[custom]'.strtoupper('$1').'[/custom]'", $content);

echo $new_content;