Search code examples
phppdostr-replacegroup-concat

Replace with array from a SELECT GROUP_CONCAT


I am trying to do a str_replace without success.. for some reason the data from MySql isn't working inside the str_replace function...

Code to bring all strings which will be used to replace the string:

$aspas = "'";
$sql2 = '
SELECT
    GROUP_CONCAT(
        DISTINCT CONCAT("'.$aspas.'", prefixo, "-'.$aspas.','.$aspas.'-", posfixo, "'.$aspas.'") 
    ) AS prefixo_posfixo
FROM
    profissionais
';

$stm2 = $pdo->prepare($sql2);
$stm2->execute();
$resultado = $stm2->fetch();

Produces with no error this output:

echo $resultado[0] >> 'dr-','-advogado','dra-','-advogada'

But when I try to insert inside the str_replace function :

$newstring = str_replace([$resultado[0]], '', 'dra-flavia-barao-advogada');
echo newstring >> dra-flavia-barao-advogada

As you see, the result keep the same, it doesn't replace the string ;(

I think it is something about convert the array to string, but the $resultado[0] isn't in a array format so I cant implode...

Do you know what I am doing wrong?


Solution

  • I forgot to post the solution before, There is:

    //SELECT THE STRINGS TO BE USED TO REMOVE FUNCTION
    $sql2 = '
    SELECT
        GROUP_CONCAT(
            DISTINCT CONCAT(prefixo, "-,-",posfixo) 
        ) AS prefixo_posfixo
    FROM
        profissionais
    ';
    
    $stm2 = $pdo->prepare($sql2);
    $stm2->execute();
    $prefixo_posfixo = $stm2->fetch();
    
    //REPLACE / REMOVE THE STRINGS
    $newstring = str_replace(explode(",", $prefixo_posfixo[0]), '', 'dra-flavia-barao-advogada');
    
    //PRODUCES THE OUTPUT
    flavia-barao