preg_match extract text between two identifiers

Hi Guys!

Im looking at extracting text between two identifiers. For example:

{dbuser},{dbpass}

would be outputted as:

Array ([0] => dbuser [1] => dbpass)

Im trying something like this, but it doesn’t work:


$credentials = "{dbuser},{dbpass}";
preg_match_all('/\\{\\(.*?)\\}/e', $credentials, $matches);

I’m guessing my regex is incorrect - can anyone help?

Thanks.

Would something like:

<?php

$credentials = "{dbuser},{dbpass}";

preg_match("/{(.*)},{(.*)}/", $credentials, $matches);

array_shift($matches);
print_r($matches);
?>

work?

$matches will be an array, element 0 will contain the text that matched the full pattern, the actual matches will start with element 1. So I put an array_shift on $matches to shift the first element out of the array. This makes element 0 be the dbuser and element 1 be the dbpass.

It works perfect, thank you.

The only question I would ask is - if there was a space in after the comma (i.e. {dbuser} , {dbpass}) would it still work? If not is there a way around that? So that it works with and without spaces.

No, it would not.

Somebody probably has a better solution for this. Just off the top of my head I have:

<?php

$credentials = "{dbuser},{dbpass}";

preg_match("/{(.*)}(,|,\\s+){(.*)}/", $credentials, $matches);

array_shift($matches);
unset($matches[1]);
print_r($matches);
?>

In this example, your adding a match for “a comma or a comma followed by multiple spaces”. But because this is encapsulated in parenthesis, it has to be unset, thus the unset($matches[1]) line.

Another solution:

<?php

$credentials = "{dbuser}, {dbpass}";

preg_match("/{(.*)},{(.*)}/", preg_replace("/,\\s+/", ",", $credentials), $matches);

array_shift($matches);
print_r($matches);
?>

Basically you nest a preg_replace() into the preg_match(). The preg_replace() just removes any spaces after the comma before conducting the match.

Neither of these examples is all that pretty, but they should work. Someone else may have a better solution.


<?php
$credentials = '{dbuser},{dbpass}';

preg_match_all('~{([^{]+)}~', $credentials, $matches);

list($user, $pass) = $matches[1];

This should work when that are spaces too. :slight_smile: