How can PHP be modified to only display the first occurrence of a search term in a text, to prevent performance issues with repetitive search terms?
To prevent performance issues with repetitive search terms, PHP can be modified to only display the first occurrence of a search term in a text. This can be achieved by using the strpos() function to find the position of the first occurrence of the search term in the text, and then using substr() to extract and display only the portion of the text before the first occurrence of the search term.
<?php
$text = "This is a sample text with a search term. This search term should only be displayed once.";
$searchTerm = "search term";
$position = strpos($text, $searchTerm);
if ($position !== false) {
$firstOccurrence = substr($text, 0, $position + strlen($searchTerm));
echo $firstOccurrence;
} else {
echo "Search term not found in text.";
}
?>