tags:

views:

59

answers:

2

Hi all,

I'm trying to parse a DSN (from a Symfony application) using regular expressions, in order to link with a secondary application, but using the same database.

The DSN I currently have is:

mysql:dbname=my_db_name;host=localhost

with a regex of:

/^(\w+):(dbname=(\w+))?;?(host=(\w+))?/

(using preg_match()). This matches OK, but fails in my test environment because the DSN elements are switched around, thus:

mysql:host=localhost;dbname=my_testdb_name

I could just switch them round, yes :-) but I'm sure that extraction of the host and dbname parts from both DSNs is possible with a single regular expression, and I'd like to be able to enhance my knowledge at the same time ;-) Is there a way I can do this?

+1  A: 

I'd split the string on ';' then use individual regexs for each part i was interested in, on each part of the split string.

trying to do it so the regex matches which ever way round is probably a bit of overkill, and would quickly get out of control if you added a third or fourth thing to check for.

in fact you might be able to get away without actuall splitting the string.

EDIT:

Ahh just re-read the question, seems this string is part of a longer string.

so you could do this

/^(\w+):((dbname|host)=(\w+))?;?((dbname|host)=(\w+))?/

which could be reduced to:

    /^(\w+):((dbname|host)=(\w+));?+

you might need to adjust for your flavour of regex, I'm only used to .net

Sam Holder
Great stuff - thanks :-)
richsage
+1  A: 

The following expression could match the two DSN

/^(\w+):((dbname|host)=(\w+))?;?((dbname|host)=(\w+))?/

But it could match mysql:host=localhost;host=localhost too...

Fred
+1 for the note about the possible issues.
Sam Holder