$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
复制代码
前一段时间在读php-resque的源码,看到了在其中对这两个的方法的应用,感觉用的很好,用来解析redis链接的设置。
redis链接的格式是:redis://user:pass@host:port/db?option1=val1&option2=val2,是不是和URL一样,所以用以上两个方法很容易解析。
地址: https://github.com/chrisboulton/php-resque/blob/master/lib/Resque/Redis.php
代码如下:
复制代码
/**
* Parse a DSN string, which can have one of the following formats:
*
* - host:port
* - redis://user:pass@host:port/db?option1=val1&option2=val2
* - tcp://user:pass@host:port/db?option1=val1&option2=val2
*
* Note: the 'user' part of the DSN is not used.
*
* @param string $dsn A DSN string
* @return array An array of DSN compotnents, with 'false' values for any unknown components. e.g.
* [host, port, db, user, pass, options]
*/
public static function parseDsn($dsn)
{
if ($dsn == '') {
// Use a sensible default for an empty DNS string
$dsn = 'redis://' . self::DEFAULT_HOST;
}
$parts = parse_url($dsn);
// Check the URI scheme
$validSchemes = array('redis', 'tcp');
if (isset($parts['scheme']) && ! in_array($parts['scheme'], $validSchemes)) {
throw new \InvalidArgumentException("Invalid DSN. Supported schemes are " . implode(', ', $validSchemes));
}
// Allow simple 'hostname' format, which `parse_url` treats as a path, not host.
if ( ! isset($parts['host']) && isset($parts['path'])) {
$parts['host'] = $parts['path'];
unset($parts['path']);
}
// Extract the port number as an integer
$port = isset($parts['port']) ? intval($parts['port']) : self::DEFAULT_PORT;
// Get the database from the 'path' part of the URI
$database = false;
if (isset($parts['path'])) {
// Strip non-digit chars from path
$database = intval(preg_replace('/[^0-9]/', '', $parts['path']));
}
// Extract any 'user' and 'pass' values
$user = isset($parts['user']) ? $parts['user'] : false;
$pass = isset($parts['pass']) ? $parts['pass'] : false;
// Convert the query string into an associative array
$options = array();
if (isset($parts['query'])) {
// Parse the query string into an array
parse_str($parts['query'], $options);
}
return array(
$parts['host'],
$port,
$database,
$user,
$pass,
$options,
);
}
http://www.bkjia.com/PHPjc/909450.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/909450.htmlTechArticlePHP的学习--解析URL PHP中有两个方法可以用来解析URL,分别是parse_url和parse_str。 parse_url 解析 URL,返回其组成部分 mixed parse_url ( string $url [,...