tags:

views:

49

answers:

3

Just one simple, specific question:
I've got the string {var1}12345{var2}, and I want to get the variable names used.

if (preg_match("/{([a-zA-Z0-9]*)}/g", $url, $matches)) {
    print_r($matches);
}

If I remove the global flag, it works, but I only get the first variable, as expected. Why isn't it working with a global flag? It works when I'm testing it with the Regex Tester

+3  A: 

From PHP: preg_match:

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

prostynick
Aha! Wonder why they made it that way. Couldn't `preg_match()` return the number of hits on global searches too, it would still be "falsy" if there were no hits...Hmm.. Anyways. Thanks (:
peirix
+1  A: 

This should do the trick (in case you need variables in format {name}):

$url = "{var1}12345{var2}";

if (preg_match_all("/{[a-zA-Z0-9]*}/", $url, $matches)) {
    print_r($matches);
}
Ondrej Slinták
+2  A: 

Use preg_match_all to fetch several matches:

if (preg_match_all("/{([a-zA-Z0-9]*)}/", $url, $matches)) {
    print_r($matches[1]);
}
nuqqsa