How can variables be correctly incorporated into regular expressions for string replacement in PHP?

When incorporating variables into regular expressions for string replacement in PHP, it is important to properly escape the variables to prevent injection attacks and ensure the regex pattern is correctly formed. One way to do this is by using the preg_quote() function to escape special characters in the variable before using it in the regex pattern.

// Example of incorporating variables into regular expressions for string replacement in PHP
$pattern = '/\b' . preg_quote($searchTerm, '/') . '\b/';
$replacement = 'replacement_string';
$newString = preg_replace($pattern, $replacement, $originalString);