Replace with array from a SELECT GROUP_CONCAT
Asked Answered
B

1

0

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?

Buffoon answered 16/1, 2023 at 15:8 Comment(4)
Hey! Please elaborate a bit better. is echo $resultado[0] producing the correct output? And in the str_replace function, what is [$prefixo_posfixo]? The brackets around it [] seem to be a syntax error? Check the official documentation to see if you are using it correctly: php.net/manual/en/function.str-replace.phpLobster
Yea it's producing correctly output, it is echoing : 'dr-','-advogado','dra-','-advogada'Buffoon
About: [$prefixo_posfixo] is was a error typo, please look again heheBuffoon
The string 'dr-','-advogado','dra-','-advogada' does not exist in 'dra-flavia-barao-advogada' so nothing gets replaced. What are you trying to replace? Do you want resultado[0] to be in array format so you can actually use it as an array and replace dra- flavia- barao- and advogada in the string 'dra-flavia-barao-advogada'?Lobster
B
0

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
Buffoon answered 21/1, 2023 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.