preg_split没有替换?

时间:2012-02-22 18:32:31

标签: php preg-split

尝试拆分字符串,但我不想“删除”我正在搜索的内容......

字符串看起来像这样:

MDVB,94010,(555)555-5555,KHII,94015,(555)555-5555,POONHY,94010,(555)555-5555,

我想在电话号码后拆分字符串,但我不想删除号码......

现在,我有这个:

preg_split("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x", $string)

但是那个输出:

Array
(
    [0] => MDVB, 94010, 
    [1] => KHII, 94015, 
    [2] => POONHY, 94010, 
)

我认为preg_split是可以使用的东西......我还应该使用其他东西吗?

4 个答案:

答案 0 :(得分:1)

您应该使用preg_match_all()来提取字符串的部分内容。

<?php
$string = "MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,";

$res = preg_match_all("/([A-Z]+,\s+\d+,\s+\(\d{3}\) \d{3}-\d{4})/",$string,$matches);
print_r($matches);
?>

输出:

Array
(
    [0] => Array
        (
            [0] => MDVB, 94010, (555) 555-5555
            [1] => KHII, 94015, (555) 555-5555
            [2] => POONHY, 94010, (555) 555-5555
        )

    [1] => Array
        (
            [0] => MDVB, 94010, (555) 555-5555
            [1] => KHII, 94015, (555) 555-5555
            [2] => POONHY, 94010, (555) 555-5555
        )

)

答案 1 :(得分:0)

您可以使用PREG_SPLIT_DELIM_CAPTURE选项,这将导致分隔符模式中的括号表达式被捕获并返回。

$parts = preg_split("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                    $string,
                    null,
                    PREG_SPLIT_DELIM_CAPTURE);

产生的数组:

array(7) {
  [0]=>
  string(13) "MDVB, 94010, "
  [1]=>
  string(3) "555"
  [2]=>
  string(15) ", KHII, 94015, "
  [3]=>
  string(3) "555"
  [4]=>
  string(17) ", POONHY, 94010, "
  [5]=>
  string(3) "555"
  [6]=>
  string(1) ","
}

我相信这是你正在寻找的行为。

答案 2 :(得分:0)

你最好像这样使用preg_match_all:

preg_match_all("/(.*?(?:\(? (?:\d{3})? \)? [\-\s] )? \d{3}-\d{4})[^,]*(?:,|$)\s*/x",
               $string, $arr );
print_r($arr[1]);

<强>输出:

Array
(
    [0] => MDVB, 94010, (555) 555-5555
    [1] => KHII, 94015, (555) 555-5555
    [2] => POONHY, 94010, (555) 555-5555
)

答案 3 :(得分:0)

$string = "MDVB, 94010, (555) 555-5555, KHII, 94015, (555) 555-5555, POONHY, 94010, (555) 555-5555,";
preg_match_all("/[A-Za-z]+, \d+, \(\d{3}\) \d{3}-\d{4}/", $string, $matches, PREG_SET_ORDER);

结果:

var_dump($matches);

array (
  0 => 
  array (
    0 => 'MDVB, 94010, (555) 555-5555',
  ),
  1 => 
  array (
    0 => 'KHII, 94015, (555) 555-5555',
  ),
  2 => 
  array (
    0 => 'POONHY, 94010, (555) 555-5555',
  ),
)