Reversing the even-length words of a string is a common programming task that involves manipulating individual words within a sentence. In PHP, there are several approaches to achieve this, each offering different levels of complexity and flexibility.
Table of Content
Using Explode and Implode Functions
The basic approach is to split the string into an array of words using the explode() function, reverse the even-length words, and then reconstruct the string using the implode function.
Example: Here, we use explode to split the input string into an array of words, iterate through the words, reverse the even-length ones with strrev() function, and finally join the modified words back into a string using the implode() function.
<?php
function reverseWords($inputString) {
$words = explode(" ", $inputString);
for ($i = 0; $i < count($words); $i++) {
if (strlen($words[$i]) % 2 === 0) {
$words[$i] = strrev($words[$i]);
}
}
$outputString = implode(" ", $words);
return $outputString;
}
$input = "Welcome to GeeksGeeks";
$output = reverseWords($input);
echo $output;
?>
Output
Welcome ot skeeGskeeG
Using Regular Expressions
Regular expressions provide a concise way to match and manipulate text patterns. We can use a regular expression to identify even-length words and then reverse them.
Example: Here, the preg_replace_callback() function will return the string containing all the matched expression that are getting replaced with the substring returned by the callback function. For getting the string length, the strlen() function is used. Then implementing the strrev() function to reverse the string.
<?php
function reverseWords($inputString)
{
$outputString = preg_replace_callback(
"/\b\w+\b/",
function ($matches) {
return strlen($matches[0]) % 2 === 0
? strrev($matches[0])
: $matches[0];
},
$inputString
);
return $outputString;
}
$input = "Welcome to GeeksGeeks";
echo reverseWords($input);
?>
Output
Welcome ot skeeGskeeG
Using Array Map and Array Walk
Another approach to reversing even-length words in a string is by utilizing array_map() or array_walk() functions in PHP. This method is both functional and easy to understand.
Example:
<?php
function reverseEvenLengthWords($inputString) {
// Split the string into an array of words
$words = explode(' ', $inputString);
// Use array_map to reverse even-length words
$words = array_map(function($word) {
// Check if the length of the word is even
if (strlen($word) % 2 == 0) {
// Reverse the word
return strrev($word);
}
// If the length is odd, return the original word
return $word;
}, $words);
// Join the words back into a string
return implode(' ', $words);
}
// Sample usage
$inputString = "Sam is working very hard";
$outputString = reverseEvenLengthWords($inputString);
echo $outputString;
?>
Output
Sam si working yrev drah