开发者

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开发者_StackOverflow中文版 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.


<?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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜