How can strpos and substr be utilized to search for a specific word within a PHP variable and apply a link to only one occurrence?

To search for a specific word within a PHP variable and apply a link to only one occurrence, you can use the strpos function to find the position of the word in the variable and then use the substr function to insert the link at that position. By checking if the word exists in the variable and applying the link only once, you can ensure that the link is added only to the first occurrence of the word.

<?php
$variable = "This is a sample text with the word to be linked.";
$word = "word";
$link = "<a href='#'>$word</a>";

$pos = strpos($variable, $word);
if ($pos !== false) {
    $variable = substr($variable, 0, $pos) . $link . substr($variable, $pos + strlen($word));
}

echo $variable;
?>