0

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 (:
2

Use preg_match_all to fetch several matches:

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

Comments

1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.