How to split a string into two parts then join the

2019-09-16 21:17发布

问题:

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'