MrXander Posted April 27, 2008 Share Posted April 27, 2008 Hi Guys, Is there any way to reverse words with PHP, depending on what a user submits? For example, if a user enters: "I want this text reversed" It would display as either: "reversed text this want I" or, even better: "desrever txet siht tnaw I" Any help would be appreciated! Thanks. Link to comment https://forums.phpfreaks.com/topic/103185-reverse-words/ Share on other sites More sharing options...
dezkit Posted April 27, 2008 Share Posted April 27, 2008 <bdo dir="rtl">HELLO MY NAME IS MAX</bdo> or <bdo dir="ltr">HELLO MY NAME IS MAX</bdo> Link to comment https://forums.phpfreaks.com/topic/103185-reverse-words/#findComment-528513 Share on other sites More sharing options...
kenrbnsn Posted April 27, 2008 Share Posted April 27, 2008 use the strrev() function: <?php $str = 'I want this text reversed'; echo strrev($str); ?> Ken Link to comment https://forums.phpfreaks.com/topic/103185-reverse-words/#findComment-528521 Share on other sites More sharing options...
coder_ Posted April 27, 2008 Share Posted April 27, 2008 here is code that reverses letters in words: <?php $words = explode(" ", "This is a sample string"); foreach ($words as $word) { $tmp_word = ""; for ($i = strlen($word) - 1; $i >= 0; $i--) { $tmp_word .= $word[$i]; } $reversed_letters .= $tmp_word; $reversed_letters .= " "; } echo $reversed_letters; //Output: sihT si a elpmas gnirts ?> or make it more simple <?php $words = explode(" ", "This is a sample string"); $reversed_letters = ""; foreach ($words as $word) { $reversed_letters .= strrev($word) . " "; } echo ($reversed_letters); ?> Link to comment https://forums.phpfreaks.com/topic/103185-reverse-words/#findComment-528536 Share on other sites More sharing options...
kenrbnsn Posted April 28, 2008 Share Posted April 28, 2008 Or even simpler: <?php $revwords = implode(' ',array_map('strrev',explode(' ', 'This is a sample string'))); echo $revwords; ?> Ken Link to comment https://forums.phpfreaks.com/topic/103185-reverse-words/#findComment-528693 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.