求助:如何按‘, {大写字母}’规则分割指定字符串为数组
Hey there! Let's break down how to split your target string exactly the way you want it. The core challenge here is splitting on the pattern comma + space + uppercase letter without losing the uppercase letter itself—and we can use PHP's regex-based string functions to nail this.
Step-by-Step Implementation
We'll use preg_split() with a positive lookahead regex to target the right split points. Here's the code:
// Your original string $originalString = "Training bench with two arm curlers, leg curler and barbell rack, Max. load: 160kg"; // Split using regex: match ", " followed by an uppercase letter (without consuming the letter) $splitArray = preg_split('/, (?=[A-Z])/', $originalString); // Output the result print_r($splitArray);
What the Regex Does
Let's break down the regex /, (?=[A-Z])/:
,: Matches the literal comma and space that precedes the uppercase letter(?=[A-Z]): This is a positive lookahead—it checks that the next character is an uppercase letter (A-Z), but doesn't include that letter in the split separator. That's why the second array element keeps the "Max..." prefix intact.
Expected Output
When you run the code, you'll get exactly the array you wanted:
Array ( [0] => Training bench with two arm curlers, leg curler and barbell rack [1] => Max. load: 160kg )
Bonus: Handling Multiple Split Points
This solution works even if your string has multiple instances of the , [A-Z] pattern. For example, if your string was:
"Item one, Item two, Big Item three, Tiny Item four"
It would split into 4 elements, each starting with the appropriate uppercase letter.
内容的提问来源于stack exchange,提问作者Zolky

