Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 字符串操作A-B…-X-Y到Y-A-B-…-X_Php_String - Fatal编程技术网

Php 字符串操作A-B…-X-Y到Y-A-B-…-X

Php 字符串操作A-B…-X-Y到Y-A-B-…-X,php,string,Php,String,我有一个以下格式的字符串: 每个子串用“-”分隔 A-B-C…-X-Y 我的问题是如何将最后一个子字符串移动到第一个子字符串 Y-A-B-C…-X 在php中 非常感谢。以下是一些代码: // 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

我有一个以下格式的字符串:

每个子串用“-”分隔

A-B-C…-X-Y

我的问题是如何将最后一个子字符串移动到第一个子字符串

Y-A-B-C…-X

在php中


非常感谢。

以下是一些代码:

// 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);
酷小子的方式 使用“分解”拆分字符串,将结果数组的最后一个元素移到前面,然后再次将其粘合在一起:

$parts = explode('-', $str);
$last = array_pop($parts);
array_unshift($parts, $last);
$result = implode('-', $parts);
老派的方式(也更快) 使用
strrpos
查找最后一次出现的分隔符,切断一个子字符串并在其前面加上前缀:

$pos = strrpos($str, '-');
$result = substr($str, $pos + 1).'-'.substr($str, 0, $pos);

为了周五晚上的疯狂

$last = substr($str, strrpos($str, '-'));
$str = strrev($last) . str_replace($last, '', $str);

免责声明:代码假定分隔符始终存在。否则,
$str
的结果将被反转。

是一个子字符串,一个字符还是一个变量?许多字符,但不确定整个字符串中有多少“-”。谢谢。+1:比我的A版有
array\u unshift
——我的想法太过分了。我想要的是B-C…-X-Y-A,而不是我原来的帖子。所以,我选择了这个答案。感谢大家。+1为字符串操作编辑。当然,与我的一样,这假设分隔符存在。