How can you ensure that word boundaries are respected when replacing terms in arrays using PHP?

When replacing terms in arrays in PHP, it is important to ensure that word boundaries are respected to avoid unintentionally replacing partial words. One way to achieve this is by using regular expressions with word boundaries (\b) to match whole words only.

// Example code snippet to replace a term in an array while respecting word boundaries
$terms = ["apple", "pineapple", "applesauce"];
$replacement = "banana";
$search_term = "apple";

foreach ($terms as &$term) {
    $term = preg_replace("/\b$search_term\b/", $replacement, $term);
}

print_r($terms);