str_replace
does not work well with arrays the way you try to use it.
You can do the following:
- First of all, clean the chain of possible blank spaces. You can easily mistakenly write more than one blank space, and if that happens, it would knock out the logic of the program. Also, doing that you no longer have to search:
AND ()
and AND ()
, with which you search AND ()
would suffice. However, I have added two possible erroneous values to $replaceAnds
, which are AND()
and ()AND
, since it is a common mistake to forget the spaces of separation, especially when the values are concatenated.
- Then prepare an array of explicit replacements for each case.
The code would be this:
$consulta = "
SELECT * FROM equipos WHERE
() AND (( nombre='computadora' OR nombre='mouse' OR nombre='teclado' ))
AND (( departamento='Electronica' ))
() AND () AND () AND AND () () AND ()AND AND()
";
/*Limpiamos la cadena de espacios en blanco sobrantes que podrían darnos muchos problemas*/
$consulta= preg_replace('/\s+/', ' ', $consulta);;
/*Creamos un array de reemplazos explícito*/
$replaceAnds = array(
'() AND' => '',
'AND ()' => '',
'AND()' => '',
'()AND' => '',
);
$resultado = str_replace(array_keys($replaceAnds), $replaceAnds, $consulta);
echo $resultado;
You would have as a result:
SELECT * FROM equipos WHERE (( nombre='computadora' OR nombre='mouse' OR nombre='teclado' )) AND (( departamento='Electronica' ))
Note:
It is possible to improve the logic that is producing your
consult, then it should not be created like this. You should implement a
kind of intelligent query builder that knows when to create the AND
and
when not.