Skip to content

Instantly share code, notes, and snippets.

@vojtabiberle
Last active November 5, 2023 03:52
Show Gist options
  • Save vojtabiberle/a3102554d62ac288825e to your computer and use it in GitHub Desktop.
Save vojtabiberle/a3102554d62ac288825e to your computer and use it in GitHub Desktop.
DSN ultimate regex parser
<?php
define ('DSN_REGEX', '/^((?P<driver>\w+):\/\/)?((?P<user>\w+)?(:(?P<password>\w+))?@)?((?P<adapter>\w+):)?((host=(?P<host>[\w-\.]+))|(unix_socket=(?P<socket_file>[\w\/\.]+)))(:(?P<port>\d+))?((;dbname=|\/)(?P<database>[\w\-]+))?$/Uim');
@frontycore
Copy link

Thanks for great regex! In PHP 8.2 there was PHP warning:
PHP Warning: preg_match(): Compilation failed: invalid range in character class at offset 102
Escaping the dash in group fixed it:

define ('DSN_REGEX', '/^((?P<driver>\w+):\/\/)?((?P<user>\w+)?(:(?P<password>\w+))?@)?((?P<adapter>\w+):)?((host=(?P<host>[\w\-\.]+))|(unix_socket=(?P<socket_file>[\w\/\.]+)))(:(?P<port>\d+))?((;dbname=|\/)(?P<database>[\w\-]+))?$/Uim');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment