如何使用PREG_SPLIT_DELIM_CAPTURE preg_split

时间:2011-06-11 06:07:33

标签: php regex

$str = "blabla and, some more blah";
$delimiters = " ,¶.\n";
$char_buff = preg_split("/(,) /", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($char_buff);

我明白了:

Array ( 
  [0] => blabla and 
  [1] => , 
  [2] => some more blah 
)

我能够弄清楚如何使用括号来使逗号显示在自己的数组元素中 - 但是如何使用多个不同的分隔符(例如,$ delimiters变量中的那些分隔符)来执行此操作?

3 个答案:

答案 0 :(得分:6)

您需要在正则表达式上使用m修饰符:

<?php
$str = "blabla and, some more blah. Blah.\nSecond line.";
$delimiters = " ,¶.\n";
$char_buff = preg_split('/([' . $delimiters . '])/m', $str, -1,
             PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($char_buff);

您还需要使用PREG_SPLIT_NO_EMPTY,以便在连续获得两个匹配项的位置(例如逗号后跟空格),您不会得到空匹配。

<强>输出

Array
(
    [0] => blabla
    [1] =>  
    [2] => and
    [3] => ,
    [4] =>  
    [5] => some
    [6] =>  
    [7] => more
    [8] =>  
    [9] => blah
    [10] => .
    [11] =>  
    [12] => Blah
    [13] => .
    [14] => 

    [15] => Second
    [16] =>  
    [17] => line
    [18] => .
)

根据您的操作,使用strtok可能是更合适的方法。

答案 1 :(得分:2)

使用类似:

'/([,.])/'

将每个分隔符放在该方括号中。

答案 2 :(得分:0)

每个定界符表达式都必须位于其自己的组中。

print_r(preg_split('/2\d4/'      , '12345', null, PREG_SPLIT_DELIM_CAPTURE)); 
Array ( [0] => 1                            [1] => 5 )

print_r(preg_split('/(2)(\d)(4)/', '12345', null, PREG_SPLIT_DELIM_CAPTURE)); 
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )