How to use Explode and Implode Functions In PHP

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



Reversing the Even Length Words of a String in PHP

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
  • Using Regular Expressions

Similar Reads

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

Using Regular Expressions

...