Jump to content

Recommended Posts

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

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.