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
$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;
?>
Related questions
-
preg_replace str_replace number formatting
-
PHP dynamic diagram Kontostand
-
TS server PHP SA