Using php how to split the usernames,passwords,datadasename,hostname,etc into a variable.
For Example:
$db = "databasename://username:password@hostname/dbname"
$ databasename = databasename
$user = username
$pass = password
$host = hostname
$dbname = dbname
I have tried with grouping in regular expression. but I don't know how to assign the group values into the variable.
preg_match("(开发者_JS百科^([a-z]?)://([a-z]?):([a-z]?)@[a-z]?)/([a-z]*?)$)", $db , $matches);
You can do something like:
$db = "databasename://username:password@hostname/dbname";
if (preg_match("~^([a-z]+)://([a-z]+):([a-z]+)@[a-z]+/([a-z]+)\$~i",
$db , $matches))
list($ignore, $databasename, $username, $password, $dbname) = $matches;
var_dump($databasename);
var_dump($username);
var_dump($password);
var_dump($dbname);
which gives:
string(12) "databasename"
string(8) "username"
string(8) "password"
string(6) "dbname"
Or you can use named groups.
Look at
print_r($matches);
after successful match. It should become clear.
From php docs here http://pl2.php.net/preg_match :
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
You have to pick a delimiter (typically, a character that is not used with the expression). The expression should start and end with the delimiter and you can optionally append flags after the closing deliminiter. E.g.:
preg_match("~(^([a-z]?)://([a-z]?):([a-z]?)@[a-z]?)/([a-z]*?)$)~i", $db , $matches);
You should consider to widen most character ranges: a username can contain numbers and a password can contain almost anything.
I suppose that the delimiters in the string (:
, //
, @
...) won't necessarily be there if the corresponding parameters are optional.
Last but not least, as Kamil Szot already pointed out, parenthesized matches are loaded into the $matches variable.
php > preg_match("#([a-z]+)://([a-z]+):([a-z]+)@([a-z]+)/([a-z]+)$#", $var , $matches);
php > print_r($matches);
Array
(
[0] => databasename://username:password@hostname/dbname
[1] => databasename
[2] => username
[3] => password
[4] => hostname
[5] => dbname
)
精彩评论