0

I want to replace words with tagged words in text.

tbl_glossary
id  word
1   apple pie
2   apple
3   juice

The words are in array from database (MySQL). Then word gets replaced with replaced word if the word contains the same value (e.g. 'apple pie' contains 'apple').

$con = mysqli_connect(db_host, db_username, db_password, db_name);
$sql = "SELECT * FROM `tbl_glossary`";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($res)){
    $arr_taggedword[] = '<a href="#" data-toggle="tooltip" id="'.$row['id'].'">'.$row['word'].'</a>';
    $arr_word[] = $row['word'];
}

$text = "apple pie made with apple juice";

$results = $text;
foreach($arr_word as $key => $value) {
    $results = str_replace($value, $arr_taggedword[$key], $results);
}
echo $results;

Then the result is shown as

<a href="#" data-toggle="tooltip" id="1"><a href="#" data-toggle="tooltip" id="2">apple</a> pie</a> made with <a href="#" data-toggle="tooltip" id="2">apple</a> <a href="#" data-toggle="tooltip" id="3">juice</a>

'apple pie' is nested. Any idea to skip/ignore replaced words to get replaced again?

Thank you in advance.

chloe
  • 119
  • 11

1 Answers1

0

You could use the array form of strtr, it will make all your substitutions in order from largest to smallest, but also not replace any text that has already been replaced. Replace your foreach loop with:

$results = strtr($text, array_combine($arr_word, $arr_taggedword));
echo $results;

Output

<a href="#" data-toggle="tooltip" id="1">apple pie</a> made with <a href="#" data-toggle="tooltip" id="2">apple</a> <a href="#" data-toggle="tooltip" id="3">juice</a>
Nick
  • 138,499
  • 22
  • 57
  • 95