0

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.

2 Answers 2

0

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.