Tutorial :what is the best way in php to reverse letters in words



Question:

i have a string .

i want to reverse the letters in every word not reverse the words order.

like - 'my string'

should be

'ym gnirts'


Solution:1

This should work:

$words = explode(' ', $string);  $words = array_map('strrev', $words);  echo implode(' ', $words);  

Or as a one-liner:

echo implode(' ', array_map('strrev', explode(' ', $string)));  


Solution:2

echo implode(' ', array_reverse(explode(' ', strrev('my string'))));  

This is considerably faster than reversing every string of the array after exploding the original string.


Solution:3

Functionified:

<?php    function flipit($string){      return implode(' ',array_map('strrev',explode(' ',$string)));  }    echo flipit('my string'); //ym gnirts    ?>  


Solution:4

This should do the trick:

function reverse_words($input) {      $rev_words = [];      $words = split(" ", $input);      foreach($words as $word) {          $rev_words[] = strrev($word);      }      return join(" ", $rev_words);  }  


Solution:5

I would do:

$string = "my string";  $reverse_string = "";    // Get each word  $words = explode(' ', $string);  foreach($words as $word)  {    // Reverse the word, add a space    $reverse_string .= strrev($word) . ' ';  }    // remove the last inserted space  $reverse_string = substr($reverse_string, 0, strlen($reverse_string) - 1);  echo $reverse_string;  // result: ym gnirts  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »