tags:

views:

26

answers:

2

I would like to split a string by an array of delimiters, and also get feedback what the delimiter was.

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

I would like an array as return with something like this:
$return[0] = array('test','+');
$return[1] = array('string','|');

thnx in advance

+2  A: 

Take a look at the PREG_SPLIT_DELIM_CAPTURE option for preg_split()

EDIT

Example:

$mystring = 'test+string|and|hello+word';
$result = preg_split('/([\+|,])/', $mystring, null, PREG_SPLIT_DELIM_CAPTURE);
Mark Baker
thnx Mark (for answer and fast reply)!
Bokw
A: 

I did not know about PREG_SPLIT_DELIM_CAPTURE before writing my answer. It's definitely the clearer than using 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");
  }
}
pygorex1