Last Updated: September 09, 2019
·
16.61K
· leethelobster

Reverse words in a sentence - PHP

Challenge: Reverse words in a given sentence without using split and join (or the like).

PHP

$str = "The lazy dog jumped over the fox";
$spaceCount = substr_count($str, " ");
$letterIndx = 0;

// count number of spaces and then loop
for($i=0; $i<=$spaceCount; $i++) {
  // get space positions
  $spaceIndx = strpos($str, " ", $letterIndx);
  // assign word by specifying start position and length
  if ($spaceIndx == 0) {
    $word = substr($str, $letterIndx);
  } else {
    $word = substr($str, $letterIndx, $spaceIndx - $letterIndx);
  }
  // push word into array
  $myArray[] = $word;
  // get first letter after space
  $letterIndx = $spaceIndx + 1;
}
// reverse the array
$reverse = array_reverse($myArray);
// echo it out
foreach($reverse as $rev) {
  echo $rev." ";
}

DEMO
http://codepad.org/chK5mNre


Here's the code if you use split and join (or the like)

PHP

$str = "The lazy dog jumped over the fox";
$myArray = str_word_count($str, 1);
$reverse = array_reverse($myArray);
foreach ($reverse as $rev) { echo $rev." "; }

DEMO
http://codepad.org/8ZvsvZzO

4 Responses
Add your response

What about using recursion. I like it because of it's elegance.

$str = "The lazy dog jumped over the fox";

function flip_words($str) {
  $last_space = strrpos($str, " ");
  if ($last_space === FALSE) {
    echo " $str";
  }
  else {
    echo substr($str, $last_space);
    flip_words(substr($str, 0, $last_space));
  }
}

flip_words($str);
over 1 year ago ·

$s = "The lazy dog jumped over the fox";
$a = explode(" ",$s);
$a = array_reverse($a);

echo implode(" ", $a);

</code>

over 1 year ago ·

if i give the input:I am in Google.
it giving the output:Google. in am I
But the correct output is:Google in am I.
Can you manipulate your code like this.
What i am saying is it is not considering the "." in end
It prints as it is with the last but it can be printed in last yaar....

over 1 year ago ·

I think this too will fulfill the purpose?

$str="The lazy dog jumped over the fox";

$ex=explode(" ",$str);

$count=count($ex);

for($i=$count;$i>=0;$i--){

echo $ex[$i];
echo " ";
}

over 1 year ago ·