qwertymk
qwertymk

Reputation: 35274

ignore letter inside capture group

I want to ignore whitespace inside a capture group, Is there any way to do this so that:

preg_split('#test[a-zA-Z0-9\s]*test#', $str, -1, PREG_SPLIT_DELIM_CAPTURE)

On any:

'A AtestA4 testZ Z'
'A AtestA4    testZ Z'
'A AtestA 4 testZ Z'
'A AtestA4testZ Z'

All return

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

Upvotes: 0

Views: 92

Answers (1)

Passerby
Passerby

Reputation: 10070

I don't know how to archive it (and I doubt if that's possible), but here's an alternative solution:

$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));

outputs:

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"
}

On real code, you can combine the preg_split into array_map.

Upvotes: 1

Related Questions