I have a replace function, since there are many words to replace, I would like a loop to be made and the words to be replaced are extracted from a database table. I tried to write the code but it didn't work.
BEFORE:
function replaceString ($content){
$w = str_replace("apple", "banana", $content);
$w = str_replace("orange", "pear", $content);
return $w;
}
AFTER:
function replaceString ($content){
$Fruits = $mysqli->query("SELECT * FROM Fruits ORDER BY id DESC");
while($row = mysqli_fetch_array($Fruits))){
$content = str_replace($row['word'], $row['replace'], $content);
}
return $content;
}
CodePudding user response:
You need to pass $mysql into your function:
<?php
function replaceString ($mysqli, $content){
$Fruits = $mysqli->query("SELECT * FROM Fruits ORDER BY id DESC");
while($row = mysqli_fetch_array($Fruits)) {
$content = str_replace($row['word'], $row['replace'], $content);
}
return $content;
}
$string = 'An apple better then sugar, but orange not';
echo replaceString($mysqli, $string);
after this change code works. PHP mysqli online here
Result:
An banana better then sugar, but pear not
also you can to know str_replace can use arrays as parameters, so you can avoid loop:
function replaceString ($mysqli, $content){
$fruits = $mysqli->query("SELECT * FROM Fruits ORDER BY id DESC");
$rows = $fruits->fetch_all(MYSQLI_ASSOC);
return str_replace(array_column($rows, 'word'), array_column($rows, 'replace'), $content);
}
CodePudding user response:
First of all, where is $mysqli
declared ?
Then in your function,
$w = str_replace($row[word], $row[replace], $content);
should be replaced by
$content = str_replace($row[word], $row[replace], $content);
the variable $w
is of no use since there's nothing else you do with $content
, just overwrite it. Moreover, it prevents your function from working fine, as you replace only in $content
and not $w
that you return.