Spencer Mark
Spencer Mark

Reputation: 5311

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;

}

Upvotes: 0

Views: 157

Answers (3)

Hanky Panky
Hanky Panky

Reputation: 46900

$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

Upvotes: 2

Lix
Lix

Reputation: 48006

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

Upvotes: 0

Kevin Labécot
Kevin Labécot

Reputation: 1995

Use regexp to solve this problem.

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

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

Upvotes: 0

Related Questions