0

我想用一个分隔符数组来分割一个字符串,并得到关于分隔符是什么的反馈。

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

我想要一个数组作为返回,如下所示
$return[0] = array('test','+');
$return[1] = array('string','|');

提前谢谢

4

2 回答 2

3

查看preg_split()的 PREG_SPLIT_DELIM_CAPTURE 选项

编辑

例子:

$mystring = 'test+string|and|hello+word';
$result = preg_split('/([\+|,])/', $mystring, null, PREG_SPLIT_DELIM_CAPTURE);
于 2010-09-23T10:10:46.913 回答
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");
  }
}
于 2010-09-23T10:20:00.560 回答