user2652620
user2652620

Reputation: 464

array_slice, implode, explode, count, for just a string permutation?

As a beginner in php, I'm in the situation where I have to reverse the followings strings:

  1. "secondname firstname" as "firstname secondame",
  2. "secondname1 secondname2 firstname" as "firstname secondname1 secondname2"

The code works but it looks like a little bit complicated for such a function.

$name = "secondname1 secondname2 firstname";
$split = explode(" ", $name);

$last = count($split);
$firstname = $split[$last -1];
$secondnames = implode(" ",array_slice($split,-$last, $last-1));

echo implode(" ",array($firstname, $secondnames));

Do you have any idea about something simpler ?

Upvotes: 1

Views: 1124

Answers (1)

georg
georg

Reputation: 214969

You can pop the last element off the end of the array and then unshift it back to the beginning:

function last_word_first($name) {
    $x = explode(' ', $name);
    array_unshift($x, array_pop($x));
    return implode(' ', $x);
}

echo last_word_first("secondname firstname"), "\n";
echo last_word_first("secondname1 secondname2 firstname"), "\n";

Another option is a regular expression:

function last_word_first($name) {
    return preg_replace('~(.+)\s+(\S+)$~', "$2 $1", $name);
}

On a self-promo note, I've got a library that can do it like this:

$x = str($name)->split();
print $x[':-1']->prepend($x[-1])->join(' ');

Upvotes: 2

Related Questions