You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何按‘, {大写字母}’规则分割指定字符串为数组

Solution for Splitting Your String as Requested

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:35:55