1

I'm having an issue creating a function that both reverses the input string AND preserves any extra spaces in it. For example:

reverse("this is a string"); // should return: "siht si a gnirts"

And if we have something like:

reverse("this is     a string"); // then should be: "siht si     a gnirts"

But I'm hitting a brick wall mentally coming up with how to account for both. I know it should be easy .. I feel stupid :/

Here is what I have so far (only works for the first part):

function reverseWords($str) {
    return implode(' ', array_reverse(explode(' ', strrev($str)))) ;
}
Adrift
  • 58,167
  • 12
  • 92
  • 90
  • 1
    You doing a whiteboard coding interview or something? That's the only time I've ever seen this requirement – Phil Aug 20 '20 at 00:45
  • Yes, it's a whiteboard coding question in a book I'm reading. I'm preparing for the interview process. – Adrift Aug 20 '20 at 01:00
  • Perhaps the question wasn't worded very well but this isn't _"reverses the input string AND preserves any extra spaces"_. Your requirement is to reverse each word within the string, maintaining word position and spacing. Hopefully your real interview questions are clearer. Good luck! – Phil Aug 20 '20 at 01:05

1 Answers1

2

You'll want to split on space, then map each entry to the string-reversed version of itself before joining the new array back together

function reverseWords($str) {
    return implode(' ', array_map('strrev', explode(' ', $str)));
}

echo reverseWords("this is a string");
// siht si a gnirts

echo reverseWords("this is     a string");
// siht si     a gnirts

https://3v4l.org/hTle3

Phil
  • 157,677
  • 23
  • 242
  • 245