拆分字符串并获取分隔符作为返回

时间:2010-09-23 10:06:23

标签: php split explode

我想通过分隔符数组拆分字符串,并获得分隔符的反馈。

例:
$mystring = 'test+string|and|hello+word';
$result = preg_split('/\+,|/+', $mystring);

我想要一个数组作为返回这样的东西
$return[0] = array('test','+');
$return[1] = array('string','|');

提前thnx

2 个答案:

答案 0 :(得分:3)

查看preg_split()

的PREG_SPLIT_DELIM_CAPTURE选项

修改

示例:

$mystring = 'test+string|and|hello+word';
$result = preg_split('/([\+|,])/', $mystring, null, PREG_SPLIT_DELIM_CAPTURE);

答案 1 :(得分:0)

在写我的答案之前,我不知道PREG_SPLIT_DELIM_CAPTURE。它绝对比使用preg_match_all

更清晰
<?php
$s = 'a|b|c,d+e|f,g';
if (preg_match_all('/([^+,|]+)([+,|])*/', $s, $matches)) {
  for ($i = 0; $i < count($matches[0]); $i++) {
    echo("got '{$matches[1][$i]}' via delimiter '{$matches[2][$i]}'\n");
  }
}