$re = '/^(mongodb:(?:\/{2})?)((\w+?):(\w+?)@|:?@?)(\S+?):(\d+)(\/(\S+?))?(\?replicaSet=(\S+?))?$/m';
$str = 'mongodb://username:localhost:27107/adfaeadf
mongodb://username:@localhost:27107/adfaeadf
mongodb://:password@localhost:27107/adfaeadf
mongodb://:@localhost:27107/mydatabasename
mongodb://@localhost:27107/mydatabasename
mongodb://localhost:27107/mydatabasename
mongodb:username:password@localhost:27107/mydatabasename
mongodb://someUser:abc123@server-a1.host.com:41652/testdb?replicaSet=rs-some2
mongodb://someUser:abc123@server-a9.host.com:41653,server-a2.host.com:41652/testdb?replicaSet=rs-some2
mongodb://localhost:27017/test
mongodb://:x@localhost:27017/test
mongodb://127.0.0.1:27017';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php