'string manipulation A-B...-X-Y to Y-A-B-...-X
I have a string in this format:
Each substring is seperated by '-'
A-B-C...-X-Y
My question is how to move the last substring to the first as
Y-A-B-C...-X
in php
Thanks a lot.
Solution 1:[1]
Here's some code that'll do it:
// Split the string into an array
$letters = explode('-', 'A-B-C-X-Y');
// Pop off the last letter
$last_letter = array_pop($letters);
// Concatenate and rejoin the letters
$result = $last_letter . '-' . implode('-', $letters);
Solution 2:[2]
The cool kid way
Split the string with explode, move the last element of the resulting array in front, and glue it together once more:
$parts = explode('-', $str);
$last = array_pop($parts);
array_unshift($parts, $last);
$result = implode('-', $parts);
The old school way (is also faster)
Find the last occurrence of the delimiter with strrpos, cut off a substring and prepend it:
$pos = strrpos($str, '-');
$result = substr($str, $pos + 1).'-'.substr($str, 0, $pos);
Solution 3:[3]
For some Friday night craziness.
$last = substr($str, strrpos($str, '-'));
$str = strrev($last) . str_replace($last, '', $str);
Disclaimer: code assume that the delimiter always exists. Otherwise the result is $str reversed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jon |
| Solution 3 |
