Home Account

Parse PDO string into an array

07-Nov-2019 20:47:46 dennis

Tags: php

function parse_PDO_String ($pdo_str): Array {

    $ary = [];

    $parsed_url = parse_url($pdo_str);
    $ary['database'] = $parsed_url['scheme'];
    $path_parts = explode(';', $parsed_url['path']);

    foreach($path_parts as $part) {
        list($key, $value) = explode('=', $part);
        $ary[$key] = $value;
    }

    return $ary;

}

// e.g. parse_PDO_String("mysql:host=localhost;dbname=testdb");

/**
=> (
    [database] => mysql
    [host] => localhost
    [dbname] => testdb
)

*/