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

PHP preg_split按空格和逗号分割并保留逗号的实现问题

Hey there! Let's figure out why your current regex isn't keeping the commas, and fix it up.

The issue with your existing code is that your regex /[\s,]+/ treats spaces and commas as a single, non-captured delimiter block. Even though you're using PREG_SPLIT_DELIM_CAPTURE, there's no capture group in your regex to actually retain the commas—so they get swallowed up along with the spaces.

Here's the fix: we need to put commas into a capture group (so they get preserved) while treating spaces as regular delimiters that don't need to be kept. We'll also add PREG_SPLIT_NO_EMPTY to avoid any blank entries in the resulting array.

Use this code instead:

$string = "It's just me, myself, i and an empty glass of wine. Age = 21";
$split = preg_split('/\s+|(,)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

print_r($split);

Let's break down what this does:

  • \s+: Matches one or more spaces, acting as a delimiter that won't be captured (so spaces don't show up in your array)
  • |: Acts as a logical "or" between the two delimiter patterns
  • (,): Matches a single comma, wrapped in a capture group—this tells PREG_SPLIT_DELIM_CAPTURE to include the comma in your result array
  • PREG_SPLIT_NO_EMPTY: Filters out any empty strings that might pop up during splitting (like if there were leading/trailing spaces, or spaces right next to commas)

When you run this, your output will be exactly what you want:

Array
(
    [0] => It's
    [1] => just
    [2] => me
    [3] => ,
    [4] => myself
    [5] => ,
    [6] => i
    [7] => and
    [8] => an
    [9] => empty
    [10] => glass
    [11] => of
    [12] => wine.
    [13] => Age
    [14] => =
    [15] => 21
)

This works even if commas don't have spaces around them (like "me,myself"), splitting it into "me", ",", "myself" perfectly.

内容的提问来源于stack exchange,提问作者emma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:16:47