split on several chars and include them in the parts
I want to split a string on several chars (being +
, ~
, >
and @
, but I want those chars to be part of the returned parts.
I tried:开发者_运维技巧
$parts = preg_split('/\+|>|~|@/', $input, PREG_SPLIT_DELIM_CAPTURE);
The result is only 2 parts where there should be 5 and the split-char isn't part of part [1].
I also tried:
$parts = preg_split('/\+|>|~|@/', $input, PREG_SPLIT_OFFSET_CAPTURE);
The result is then 1 part too few (4 instead of 5) and the last part contains a split-char.
Without flags in preg_split
, the result is almost perfect (as many parts as there should be) but all the split-chars are gone.
Example:
$input = 'oele>boele@4 + key:type:id + *~the end'; // spaces should be ignored
$output /* should be: */
array( 'oele', '>boele', ' @4 ', '+ key:type:id ', '+ *', '~the end' );
Is there a spl function or flag to do this or do I have to make one myself =(
$parts = preg_split('/(?=[+>~@])/', $input);
See it
Since you want to have the delimiters to be part of the next split piece, your split point is right before the delimiter and this can be easily done using positive look ahead.
(?= : Start of positive lookahead
[+>~@] : character class to match any of your delimiters.
) : End of look ahead assertion.
Effectively you are asking preg_split
to split the input string at points just before delimiters.
You're missing an assignment for the limit parameter which is why it's returning less than you expected, try:
$parts = preg_split('/\+|>|~|@/', $input, -1, PREG_SPLIT_OFFSET_CAPTURE);
well i had the same problem in the past. You have to parenthese your regexp with brackets and then it hopefully works
$parts = preg_split('/(\+|>|~|@)/', $input, PREG_SPLIT_OFFSET_CAPTURE);
and here is it explained: http://www.php.net/manual/en/function.preg-split.php#94238
Ben is correct.
Just to add to his answer, PREG_SPLIT_DELIM_CAPTURE
is a constant with value of 2 so you get 2 splits, similarly PREG_SPLIT_OFFSET_CAPTURE
has a value of 4.
精彩评论