【问题标题】:How to split a string into two parts then join them in reverse order as a new string?如何将字符串拆分为两部分,然后以相反的顺序将它们连接为新字符串?
【发布时间】:2017-07-03 11:01:31
【问题描述】:
这是一个例子:
$str="this is string 1 / 4w";
$str=preg_replace(?); var_dump($str);
我想在这个字符串中捕获1 / 4w 并将这部分移动到字符串的开头。
结果:1/4W this is string
只要给我包含捕获的变量。
最后一部分1 / 4W 可能不同。
例如1 / 4w 可以是 1/ 16W 、 1 /2W 、 1W 或 2w
字符W可以是大写也可以是小写。
【问题讨论】:
标签:
php
string
preg-replace
substring
capture-group
【解决方案1】:
如果要捕获子字符串,请使用capture group:
$str = "this is string 1 / 4w"; // "1 / 4w" can be 1/ 16W, 1 /2W, 1W, 2w
$str = preg_replace('~^(.*?)(\d+(?:\s*/\s*\d+)?w)~i', "$2 $1", $str);
var_dump($str);
【解决方案2】:
没有看到一些不同的样本输入,似乎第一个子字符串中没有数字。出于这个原因,我使用否定字符类来捕获第一个子字符串,省略定界空格,然后将字符串的其余部分捕获为第二个子字符串。这使我的模式非常高效(比 Toto 的模式快 6 倍,并且没有逗留的空白字符)。
Pattern Demo
代码:
$str="this is string 1 / 4w";
$str=preg_replace('/([^\d]+) (.*)/',"$2 $1",$str);
var_export($str);
输出:
'1 / 4w this is string'