revolt_101
revolt_101

Reputation: 395

php preg_split: split string by lowercase letters surrounded by undrscores

I need to split a string by lowercase letters surrounded by underscores while keeping the delimiter. For example, if I have this string:
$string = '1_and_2_not_3';
The desired output would be:

[
  0 => "1",
  1 => "_and_2",
  2 => "_not_3"
]

Right now, I'm doing this:
$stringArray = preg_split('/[_(.*?)_]/u', $string, PREG_SPLIT_DELIM_CAPTURE); However, it's not capturing the whole delimiter and its only catching the first match.

[
  0 => "1",
  1 => "and_2_not_3"
]

What regex expression would catch all matches plus give me the full delimiter?

Upvotes: 1

Views: 233

Answers (1)

hwnd
hwnd

Reputation: 70732

You can split using a lookahead, asserting the position of an underscore then lowercase letter.

$results = preg_split('/(?=_[a-z])/', $str);

eval.in

Upvotes: 3

Related Questions