Mike
Mike

Reputation: 1738

Creating Regular Expression to search a string

I have a string that contains variables in the format {namespace:name} I am trying to create a regular expression for finding all of the variables in the string. I have the following so far, but it isn't working:

$str = " {user:fname} and the last name = {user:lname}";
var_dump(preg_match_all("/^\{(\w):(\w)\}/", $str, $matches));   
var_dump($matches);

But it isn't finding any of the tags. The variables can have any word for namespace and name, but letters only with no spaces. Any help would be appreciated.

Update

I tried the following also and received no results: "/\{(\w):(\w)\}/"

Upvotes: 0

Views: 55

Answers (1)

Toto
Toto

Reputation: 91375

Remove the anchor ^ from the regex and allow variables with a length of more than one character.

/^\{(\w):(\w)\}/

becomes:

/\{(\w+):(\w+)\}/

Upvotes: 5

Related Questions