开发者

string manipulation A-B...-X-Y to Y-A-B-...-X

开发者 https://www.devze.com 2023-04-05 06:26 出处:网络
I have a string in this format: Each substring is seperated by \'-\' A-B-C...-X-Y My quest开发者_运维知识库ion is how to move the last substring to the first as

I have a string in this format:

Each substring is seperated by '-'

A-B-C...-X-Y

My quest开发者_运维知识库ion is how to move the last substring to the first as

Y-A-B-C...-X

in php

Thanks a lot.


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);


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);

See both in action.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消