-1

How to reverse words present in string in PHP?

Example:

I am working in Google.

It should display the output as reversing first and last word and second word to fourth word and so on and the middle word should be same and should also display the number of words.

Output Example:

Google in working am i. 
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Sonnu
  • 37
  • 4

3 Answers3

12

Split the sentence on spaces, reverse the array, and join them on spaces:

echo implode(' ', array_reverse(explode(' ', $str)));
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

You should do it like this:

  • split the string into array of words
  • rearrange the array into the sequence you need
  • join the array back into a string.
naivists
  • 32,681
  • 5
  • 61
  • 85
0

You can use the following piece of code to achieve your desired results:

Code:

<?php
$string="I am working in Google";//Declaring string
print_r (implode(' ', array_reverse((explode(" ",$string)))));//converting string into array then reversing and then converting back into string
?>

Output:

Google in working am I
atif
  • 87
  • 1
  • 3