Php 忽略捕获组中的字母

Php 忽略捕获组中的字母,php,regex,Php,Regex,我想忽略捕获组中的空白,有没有办法做到这一点: preg_split('#test[a-zA-Z0-9\s]*test#', $str, -1, PREG_SPLIT_DELIM_CAPTURE) 在任何情况下: 'A AtestA4 testZ Z' 'A AtestA4 testZ Z' 'A AtestA 4 testZ Z' 'A AtestA4testZ Z' 全部返回 array( [0] => 'A A', [1] => 'testA4',

我想忽略捕获组中的空白,有没有办法做到这一点:

preg_split('#test[a-zA-Z0-9\s]*test#', $str, -1, PREG_SPLIT_DELIM_CAPTURE)
在任何情况下:

'A AtestA4 testZ Z'
'A AtestA4    testZ Z'
'A AtestA 4 testZ Z'
'A AtestA4testZ Z'
全部返回

array(
    [0] => 'A A',
    [1] => 'testA4',
    [2] => 'Z Z'
)

我不知道如何存档(我怀疑这是否可行),但这里有一个替代解决方案:

$str='A AtestA 4 testZ Z';
$arr=preg_split('#(test[a-zA-Z0-9\s]*test)#', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
var_dump($arr); //just to debug (compare)
var_dump(array_map(function($v){
    if(preg_match('#test[a-zA-Z0-9\s]*test#',$v))
        return str_replace(' ','',preg_replace('#(test[a-zA-Z0-9\s]*)test#','\1',$v));
    else
        return $v;
},$arr));
产出:

array(3) {
  [0]=>
  string(3) "A A"
  [1]=>
  string(12) "testA 4 test"
  [2]=>
  string(3) "Z Z"
}
array(3) {
  [0]=>
  string(3) "A A"
  [1]=>
  string(6) "testA4"
  [2]=>
  string(3) "Z Z"
}

在真实代码中,你可以将
preg_split
组合成
array_map

你的意思是
preg_match()
,而不是
preg_replace()
?@Barmar Oops,我实际上是说split你不清楚你想要什么,但你可能要求断言
(?=…)