Replacing word in wordpress Search not working Properly

Your code says, “If the search term isn’t empty, and that exact search term is in my search replacements array, then replace the term.” So, instead of this:

!empty($search_replacements[$request_vars['s']]

(which means, if this exact search term [$request_vars['s'] is in my $search_replacements array)

you’ll need to instead loop through your search replacements array every time someone searches, and in the loop check whether the current search term is a substring of the current key in the loop. If so, then do your replacement – but only replace the substring and not the full string.

So, you’ll need something like this:

<?php
function modify_search_term($request_vars) {
    // Global is usually not ideal - include the terms inside your filter.
    $search_replacements = array(
        '-' => ' ',
        '&' => 'replace2',
        'var' => 'foo'
    );
    // Loop through all of the Search Replacements
    foreach($search_replacements as $key => $replacement) {
        // Check for current Key in the Search Term
        if(stripos($request_vars['s'], $key)) {
            // Replace the Key with the Replacement - but don't affect the rest of the Search Term
            $request_vars['s'] = str_replace($key, $replacement, $request_vars['s']);
        }
    }
    // Always return
    return $request_vars;
}
add_filter('request', 'modify_search_term');
?>