How can PHP prevent nested links and ensure that each keyword is only linked once in a given text?

To prevent nested links and ensure each keyword is only linked once in a given text, we can use regular expressions to identify keywords and check if they have already been linked. We can also keep track of the keywords that have been linked using an array to avoid linking them again.

function linkKeywordsOnce($text, $keywords) {
    $linkedKeywords = array();
    
    foreach($keywords as $keyword) {
        if(!in_array($keyword, $linkedKeywords)) {
            $text = preg_replace('/\b' . $keyword . '\b/', '<a href="#">' . $keyword . '</a>', $text, 1);
            $linkedKeywords[] = $keyword;
        }
    }
    
    return $text;
}

$text = "This is a sample text with keywords PHP, nested, PHP, linked only once.";
$keywords = array("PHP", "nested", "linked");

echo linkKeywordsOnce($text, $keywords);