Open In App

Reversing the Even Length Words of a String in PHP

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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




<?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




<?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





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads