Home Account

Parse PDO string into an array

2019-11-07 20:47 dennis iversen

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
)

*/

This page has been requested 2619 times