What are the best practices for handling word boundaries in preg_replace when dealing with special characters like umlauts?

When dealing with special characters like umlauts in preg_replace, it is important to consider word boundaries to ensure that replacements are applied correctly. One way to handle this is by using the \b anchor in the regular expression pattern to match word boundaries. This ensures that replacements are only made at the beginning or end of words, preventing unintended changes within words.

$text = "Möglichkeit Morgen Möbel";
$pattern = '/\bM\b/u'; // Match only the word "M"
$replacement = 'X';
$new_text = preg_replace($pattern, $replacement, $text);
echo $new_text; // Output: "Xöglichkeit Xorgen Möbel"