简体   繁体   中英

PHP Url string to array

I'm trying to find out if there's any function that would split a string like:

keyword=flower|type=outdoors|colour=red

to array:

array('keyword' => 'flower', 'type' => 'outdoors', 'colour' => 'red')

At the moment I built a custom function, which uses explode to first split elements with the separator | and then each of those with assignment symbol = , but is there perhaps a native function which would do it out of the box by specifying the string separator?

The function I've written looks like this:

public static function splitStringToArray(
    $string = null,
    $itemDivider = '|',
    $keyValueDivider = '='
) {

    if (empty($string)) {

        return array();

    }

    $items = explode($itemDivider, $string);

    if (empty($items)) {

        return array();

    }

    $out = array();

    foreach($items as $item) {

        $itemArray = explode($keyValueDivider, $item);

        if (
            count($itemArray) > 1 &&
            !empty($itemArray[1])
        ) {

            $out[$itemArray[0]] = $itemArray[1];

        }

    }

    return $out;

}
$string = "keyword=flower|type=outdoors|colour=red";
$string = str_replace('|', '&', $string);
parse_str($string, $values);
$values=array_filter($values);   // Remove empty pairs as per your comment
print_r($values);

Output

Array
(
    [keyword] => flower
    [type] => outdoors
    [colour] => red
)

Fiddle

Use regexp to solve this problem.

([^=]+)\=([^\|]+)

http://regex101.com/r/eQ9tW8/1

The issue is that your chosen format of representing variables in a string is non-standard. If you are able to change the | delimiter to a & character you would have (what looks like) a query string from a URL - and you'll be able to parse that easily:

$string = "keyword=flower&type=outdoors&colour=red";
parse_str( $string, $arr );
var_dump( $arr );

// array(3) { ["keyword"]=> string(6) "flower" ["type"]=> string(8) "outdoors" ["colour"]=> string(3) "red" }

I would recommend changing the delimiter at the source instead of manually replacing it with replace() or something similar (if possible).

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