What is the best way to automatically link words in a text based on a MySQL database in PHP?

One way to automatically link words in a text based on a MySQL database in PHP is to use regular expressions to identify the words in the text and then query the database to check if those words exist as links. If they do, you can replace the words in the text with the corresponding link.

<?php

// Assuming $text contains the text to be processed
// Assuming $db is the MySQL database connection

// Use regular expression to find words in the text
preg_match_all('/\b\w+\b/', $text, $matches);

// Loop through each word found
foreach($matches[0] as $word) {
    // Query the database to check if the word exists as a link
    $query = "SELECT link FROM links_table WHERE word = '$word'";
    $result = mysqli_query($db, $query);
    
    // If a link is found, replace the word in the text with the link
    if(mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $text = str_replace($word, '<a href="' . $row['link'] . '">' . $word . '</a>', $text);
    }
}

// Output the text with links
echo $text;

?>