John
John

Reputation: 45

Split a string with repeating pattern, retaining delimiter

Let's say we have a command parser input whereby a given character (a dot in this case) serves two functions: to split up strings into other commands and also to instruct the parser to repeat the last command.

For example:

go north.pick up item.go west...go north..

What this would achieve is "go north, pick up item, go west three times, go north twice". However, when using preg_split I simply cannot get the desired output.

All I have up to now is:

$temp = 'go north.pick up item.go west...go north..';
preg_split('/\.)/', $temp);

which yields:

Array
(
[0] => go north
[1] => pick up item
[2] => go west
[3] =>
[4] =>
[5] => go north
[6] =>
[7] =>
)

This is obviously incorrect in two instances - no dots returned and an extra command at the end. The dots must be returned so our parser can work out the user wants to repeat their last command.

Using PREG_SPLIT_DELIM_CAPTURE does not fare any better, despite using (\.) as the regex.

Upvotes: 1

Views: 824

Answers (2)

NikiC
NikiC

Reputation: 101936

preg_match_all('~([^.]+)(\.+)~', $input, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    // $match[1] is what to do and $match[2] contains the dots.
    echo 'Do ', $match[1], ' ', strlen($match[2]), ' times', "\n";
}

See preg_match_all for further reference.

Upvotes: 0

etarion
etarion

Reputation: 17141

<?php

$temp = 'go north.pick up item.go west...go north..';
preg_match_all('/[^.]*\./', $temp, $r);
var_dump($r);

See http://ideone.com/a7o7v for a demonstration of the output.

Upvotes: 1

Related Questions