Skip to content
PHP Logo

What are best practices for dynamically counting and manipulating words in a text string using PHP?

When dynamically counting and manipulating words in a text string using PHP, it is important to first break down the string into individual words, perform the necessary operations, and then reassemble the modified text. This can be achieved by using PHP functions like explode() to split the string into an array of words, manipulating the words as needed, and then using implode() to join the words back into a single string.

php
// Sample text string
$text = "This is a sample text string.";

// Split the text into an array of words
$words = explode(" ", $text);

// Count the number of words
$num_words = count($words);

// Manipulate the words (e.g. convert to uppercase)
foreach($words as $key => $word) {
    $words[$key] = strtoupper($word);
}

// Reassemble the modified text
$new_text = implode(" ", $words);

// Output the modified text
echo $new_text;