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. Quote 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> Quote 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 Quote 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); ?> Quote 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 Quote Link to comment https://forums.phpfreaks.com/topic/103185-reverse-words/#findComment-528693 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.