开发者

Using PHP and regex, insert a character between a group of matched characters

I would like to insert a character between a group of matched characters using regex to define the group and PHP to place the character within the match. Looking here, I see that it may require PHP recursive matching, although I imagine there could be a simpler wa开发者_运维问答y.

To illustrate, I am attempting to insert a space in a string when there is a combination of 2 or more letters adjacent to a number. The space should be inserted between the letters and number(s). The example, "AXR900DE3", should return "AXR 900 DE 3".

Could an answer be to use preg_split to break up the string iteratively and insert spaces along the way? I've begun an attempt using preg_replace below for the pattern 2+letters followed by a number (I will also need to use a pattern, a number followed by 2+letters), but I need another step to insert the space between that match.

$sku = "AXR900DEF334";
$string = preg_replace('/(?<=[A-Z]{2}[\d])/',' ', $sku);


You don't need to do recursive. If I have understood you correctly, you should be able to do this:

$sku = "AXR900DEF334";
$string = preg_replace('/((?<=[A-Z]{2})(?=[0-9])|(?<=[0-9])(?=[A-Z]{2}))/',' ', $sku);
echo $string;

OUTPUT

AXR 900 DEF 334

This will match both when the letters precedes and comes after the digits.


Try this php code:

<?php
$sku = "AXR900DEF334";
$s = preg_replace('/(?<=[A-Z]{2})([\d])/', ' $1', $sku);
var_dump($s);
?>

OUTPUT

string(14) "AXR 900DEF 334"


Try this:

<?php
$sku = "AXR900DEF334";
$string = preg_replace('/([A-Z]{2,})([\d])/','\1 \2', $sku);
echo "$string\n";
?>


You may need to use two expressions:

Add a space between characters and numbers:

$sku = "AXR900DEF334";
$sku = preg_replace('/([A-Z]{2,})([\d])/','\1 \2', $sku);

And then add a space between numbers and characters:

$sku = preg_replace('/([\d])([A-Z]{2,})/','\1 \2', $sku);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜