• Instead of using replace use CASE WHEN ... THEN END syntex

    like

    and $filter = CASE WHEN CONDITION THEN 'VALUE' ELSE 'VALUE' END