Hwo to use str_replace in php to replace value

$array = "php, html, flash, css, bootstrap";
$stringDrivenFromTheDatabase = "does php and html still good in 2019 orwhat;

what I want is to check the if one or more values from the array matches the string-driven from the database what i want is to

str_replace($array, '<a href="'.$TheWordThatMatchedFromTheArrayAbove'">$TheWordThatMatchedFromTheArrayAbove</a>';

Okay so first, you’ll need a real array, not a string with comma separated values.
Second, run a foreach loop like so:

foreach($array as $word){
$string = str_replace($word, "WHATEVER HREF", $string);
}
1 Like

this code just loop the string over and over again

foreach($array as $word){
$string = str_replace($word, “WHATEVER HREF”, $string);
echo $string;
}
the string will be printed again and again until it reach the munt of string that in the array and thas is bad and not what i want

But, with a bit of logic, you would’ve figured out that the echo code should have been placed after the end of the foreach loop :wink:

// foreach will replace all the words in $string that match with the ones in $array
// do note that we are using the same string over and over again, that's why it's useless to echo the string in the foreach loop, because the end result is already being progressively made in the $string variable
foreach($array as $word){
    $string = str_replace($word, “WHATEVER HREF”, $string);
}
// echo the final result
echo $string;

Fun fact: Math is very important in terms of making you think the right way. In order to be a successful programmer, you need maths.

2 Likes

will am very good at math but I’ve never thought of using the echo outside the foreach and up until now I didn’t think it possible hehe lol. but thanks anyway bro for the help.

1 Like

No problem :slight_smile: