简体   繁体   中英

How can I use preg_match_all() to convert a string with 2 delimiters into an associative array?

I rarely uses regular expressions, but think I might have a situation that calls for them nicely (using preg_match_all).

Input:

10 - RIGHT SIDE|Validated,11 - ENTRY DOOR|Validated,20 - ENTRY DOOR|Not Validated

I am attempting to split each array index on the comma, and ideally, the key would be the text before the pipe, and the value the text after the pipe in each split.

Expected output:

array(0): key(10 - RIGHT SIDE) => value(Validated)
array(1): key(11 - ENTRY DOOR) => value(Validated)
array(2): key(20 - ENTRY DOOR) => value(Not Validated)

This will always be in a single long string of text.

Here is what I tried:

preg_match_all('/([^|]*?):([^,]*),?/', $strPoints, $arrPoints);
$out = array_combine($arrPoints[1], $arrPoints[2]);

Which gave me something close (truncated the output):

Array
(
    [29 - Em Exit] =>  ENTERTAINMENT AREA|Not Validated
    [35 - Em Exit] =>  ENTERTAINMENT AREA|Validated
    [36 - Em Exit] =>  ENTERTAINMENT AREA|Validated
)

This should work for you:

You don't really need a regex for this. First just explode() your string into an array by a comma. So that you have an array, eg

Array
(
    [0] => 10 - RIGHT SIDE|Validated
    [1] => 11 - ENTRY DOOR|Validated
    [2] => 20 - ENTRY DOOR|Not Validated
)

After this you go through each array element with array_map() and explode it again, but this time by a pipe. Then you will end up with this array:

Array
(
    [0] => Array
        (
            [0] => 10 - RIGHT SIDE
            [1] => Validated
        )

    [1] => Array
        (
            [0] => 11 - ENTRY DOOR
            [1] => Validated
        )

    [2] => Array
        (
            [0] => 20 - ENTRY DOOR
            [1] => Not Validated
        )

)

And at the end you can simply use array_column() to use the 0 column as key and 1 as value.

So the full code would look something like this:

<?php

    $str = "10 - RIGHT SIDE|Validated,11 - ENTRY DOOR|Validated,20 - ENTRY DOOR|Not Validated";

    $arr = array_column(array_map(function($v){
        return explode("|", $v);
    }, explode(",", $str)), 1, 0);

    print_r($arr);

?>

output:

Array
(
    [10 - RIGHT SIDE] => Validated
    [11 - ENTRY DOOR] => Validated
    [20 - ENTRY DOOR] => Not Validated
)

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