Skip to content
PHP Logo

What is the best approach to replacing every 3rd word in a text using PHP?

To replace every 3rd word in a text using PHP, you can split the text into an array of words, loop through the array, and replace every 3rd word with a new word. You can achieve this by using the `explode()` function to split the text into an array of words, then iterate through the array and use a counter to determine if the current word is the 3rd word. If it is, replace it with a new word.

php
<?php
$text = "This is a sample text to demonstrate replacing every 3rd word.";
$words = explode(" ", $text);
$counter = 0;
$newWord = "REPLACEMENT";

foreach($words as &$word) {
    $counter++;
    if($counter % 3 == 0) {
        $word = $newWord;
    }
}

$newText = implode(" ", $words);
echo $newText;
?>