开发者

PHP preg_split anyway to keep the dividing string ??

If i have the following string

$string = "
0001

a
b
c
开发者_运维知识库d
e

0002

f
g
h
i
j
";

I am splitting it with $r = preg_split("/\d{4}\n/", $string); and that works fine but i also want to include the dividing string..

i.e. at the moment this gives me

Array [0] {

a
b
c
d
e
}

 => [1] {

f
g
h
i
j
}

but i want it to include the divider i.e.

Array [0] {
0001

a
b
c
d
e
}

 => [1] {
0002

f
g
h
i
j
}

Hope that makes sense..

Thanks

Lee


You could use a lookahead [docs]:

preg_split("/(?=\d{4})/", $string, -1, PREG_SPLIT_NO_EMPTY)

DEMO

Don't know why you have <br/> in your expression. There is no HTML in your string (at least not in this example).


Use preg_match_all instead.

preg_match_all("/\d{4}[^\d]+/", $string, $matches);

The matches will contain all the parts of your string that start with 4 digits and end right before the next digit.

You also may filter out the <br> using brackets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜