Reputation: 11
I'm looking for a way to split the following string after each set of numbers using regex. I am fairly new to this and I'm having a hard time understanding how to use the correct regex format.
$string = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';
preg_split("/([0-9])/", $string, 0, PREG_SPLIT_NO_EMPTY);
Upvotes: 1
Views: 322
Reputation: 47904
Match one or more digits, forget that you matched them (\K
), then explode on the next space. Demo
$str = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';
var_export(
preg_split('/\d+\K /', $str)
);
Clean output with no trailing spaces:
array (
0 => '521158525',
1 => 'Interest Being Subordinated: 521855248',
2 => 'Benefiting Interest: 511589923',
)
Upvotes: 0
Reputation: 163362
To split after each set of numbers, you might use a pattern to match only digits between word boundaries.
Then use \K
to forget what is matched until so far follwed by matching optional horizontal whitespace chars to not get trailing whitespaces after the split.
$string = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';
$result = preg_split(
"\b\d+\b\h*\K",
$string,
0,
PREG_SPLIT_NO_EMPTY
);
print_r($result);
Output
Array
(
[0] => 521158525
[1] => Interest Being Subordinated: 521855248
[2] => Benefiting Interest: 511589923
)
Upvotes: 1
Reputation: 10163
May be you need to add one more flag PREG_SPLIT_DELIM_CAPTURE
to function call:
<?php
$string = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';
$res = preg_split("/:?\s*([0-9]+)\s?/", $string, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
var_export($res);
Result:
array (
0 => '521158525',
1 => 'Interest Being Subordinated',
2 => '521855248',
3 => 'Benefiting Interest',
4 => '511589923',
)
Upvotes: 0