How to split a string into two parts then join them in reverse order as a new string?

人盡茶涼 提交于 2019-12-12 03:55:00

问题


This is an example:

$str="this is string 1 / 4w";
$str=preg_replace(?); var_dump($str);

I want to capture 1 / 4w in this string and move this portion to the begin of string.

Result: 1/4W this is string

Just give me the variable that contains the capture.

The last portion 1 / 4W may be different.

e.g. 1 / 4w can be 1/ 16W , 1 /2W , 1W , or 2w

The character W may be an upper case or a lower case.


回答1:


Use capture group if you want to capture substring:

$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:


Without seeing some different sample inputs, it seems as though there are no numbers in the first substring. For this reason, I use a negated character class to capture the first substring, leave out the delimiting space, and then capture the rest of the string as the second substring. This makes my pattern very efficient (6x faster than Toto's and with no linger white-space characters).

Pattern Demo

Code:

$str="this is string 1 / 4w";
$str=preg_replace('/([^\d]+) (.*)/',"$2 $1",$str);
var_export($str);

Output:

'1 / 4w this is string'


来源:https://stackoverflow.com/questions/44883916/how-to-split-a-string-into-two-parts-then-join-them-in-reverse-order-as-a-new-st

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!