【问题标题】:PHP preg_split anyway to keep the dividing string ??PHP preg_split 无论如何都要保留分割字符串?
【发布时间】:2011-07-30 12:56:18
【问题描述】:

如果我有以下字符串

$string = "
0001

a
b
c
d
e

0002

f
g
h
i
j
";

我用$r = preg_split("/\d{4}\n/", $string); 分割它,效果很好,但我也想包含分割字符串..

即目前这给了我

Array [0] {

a
b
c
d
e
}

 => [1] {

f
g
h
i
j
}

但我希望它包含分隔符,即

Array [0] {
0001

a
b
c
d
e
}

 => [1] {
0002

f
g
h
i
j
}

希望这是有道理的..

谢谢

李

【问题讨论】:

    标签: php arrays preg-match explode preg-split


    【解决方案1】:

    你可以使用lookahead [docs]:

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

    DEMO

    不知道为什么你的表情中有<br/>。您的字符串中没有 HTML(至少在本例中没有)。

    【讨论】:

      【解决方案2】:

      改用 preg_match_all。

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

      匹配项将包含字符串中以 4 位数字开头并在下一个数字之前结束的所有部分。

      您也可以使用括号过滤掉<br>。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-29
        • 1970-01-01
        相关资源
        最近更新 更多