What best practices should be followed when using preg_replace in PHP to replace specific patterns within text, such as converting YouTube video links to embedded iframes?

When using preg_replace in PHP to replace specific patterns within text, such as converting YouTube video links to embedded iframes, it is important to use proper regular expressions to accurately match the patterns. Additionally, it is recommended to sanitize the input to prevent any potential security vulnerabilities. Finally, testing the functionality thoroughly with different scenarios is crucial to ensure the replacement is done correctly.

<?php
$text = "Check out this YouTube video: https://www.youtube.com/watch?v=ABC123";
$pattern = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/';
$replacement = '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
$updated_text = preg_replace($pattern, $replacement, $text);
echo $updated_text;
?>