简体   繁体   中英

preg_split get delimiters in an array

Is it possible when using preg_split to return the delimiters into an array in the order that they were found?

So take this for example:

$string = "I>am+awesome";
preg_split("/>|\+/", $string);

and then get an output somewhat like this:

Array(
    Array(
        0 => "I",
        1 => "am",
        2 => "awesome"
    ),
    Array (
        0 => ">"
        1 => "+"
    )
)

I realize that I could do the split, and then loop through the original string and add them as they are found, but I am looking for a better way if there is one.

Use a capture group () and PREG_SPLIT_DELIM_CAPTURE :

preg_split("/(>|\+)/", $string, 0, PREG_SPLIT_DELIM_CAPTURE);

Or as @hsz states (>|\\+) would be a better pattern.

Here is a way to achieve this with lookahead and without using PREG_SPLIT_DELIM_CAPTURE to make this regex work on other platforms like Java where there is no such flag:

print_r( preg_split('/(?<=[>|+])|(?=[>|+])/', $string ) );
Array
(
    [0] => I
    [1] => >
    [2] => am
    [3] => +
    [4] => awesome
)
$str = "I+>amaw+e+s>om>e";
$matches =  preg_split("/(>|\+)/",$str);
$all_matches = preg_split("/(>|\+)/", $str ,null, PREG_SPLIT_DELIM_CAPTURE);
$delimeters_order = array_diff($all_matches,$matches);
var_dump($delimeters_order);

array(6) {
 [1]=>
 string(1) "+"
 [3]=>
 string(1) ">"
 [5]=>
 string(1) "+"
 [7]=>
 string(1) "+"
 [9]=>
 string(1) ">"
 [11]=>
 string(1) ">"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM