Skip to content

Instantly share code, notes, and snippets.

@moolex
Last active December 10, 2015 22:08
Show Gist options
  • Save moolex/4500194 to your computer and use it in GitHub Desktop.
Save moolex/4500194 to your computer and use it in GitHub Desktop.
DSN 字符串解析
<?php
/**
* DSN 字符串解析
* @param string $dsn
*/
function dsn_resolver($dsn)
{
preg_match('/^([a-z]+)\:\/\/(\w+)[\:]?(\w+)?[@]+([\w|\.]+)?[\:]?([0-9]+)?[\/]?(\w+)$/i', $dsn, $matchs);
if ($matchs)
{
$data = array();
$ks = array('dsn', 'driver', 'username', 'password', 'host', 'port', 'database');
foreach ($matchs as $i => $item)
{
$data[$ks[$i]] = $item;
}
return $data;
}
else
{
return false;
}
}
function display($dsn)
{
$data = dsn_resolver($dsn);
if ($data)
{
echo '<pre>';
echo 'DSN: '.$data['dsn']."\n";
foreach ($data as $k => $v)
{
if ($k != 'dsn')
{
echo $k.'='.$v.' / ';
}
}
echo "\n".'-----------------'."\n";
echo '</pre>';
}
else
{
echo '<pre>DSN: '.$dsn.' - Resolve False</pre>';
}
}
display('mysql://root@localhost/mysql');
display('mysql://root:pass@localhost:3306/mysql');
display('mongo://admin:admin@uuland.org:8888/local');
display('redis://connect@uuland.org/cache');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment