views:

46

answers:

4

Hi,

I want to get the template words in a string. Template in the sense of words in {} inside a string. I am adding here a code to explain what I want exactly.

$string = "Hi {username}, Here is your {password}";

function get_template_variables($string)
{

    ....
    ....
    return array();
}

$result = get_template_variables($string);
print_r($result);


array[
    0 => username,
    1 => password
    ]

I hope you understand what I need. I need the definition program to be used inside the get_template_variables($string) method

+4  A: 
function get_template_variables($string) {
    preg_match_all('/{([^}]+)}/', $string, $matches);
    return $matches[1];
}
Sean Bright
No need to check whether `preg_match_all` found any matches, with the default *PREG\_PATTERN\_ORDER* mode `$matches[1]` is always an array.
Gumbo
Sure enough. Updated.
Sean Bright
+2  A: 

You can do:

function get_template_variables($string) {

    if(preg_match_all('/\{(.*?)\}/',$string,$m)) {
        return $m[1]
    }
    return array();
}
codaddict
Awesome! The above two methods are working. Sean Bright and Codaddict - real quick answers: Thank you all.
Abu Sithik
A: 
  1. Search for '{' character positions and save them in an array.
  2. Search for '}' character positions and save them in another array.
  3. Check if the data is valid:
    • If both arrays have different sizes, the template has something wrong with it.
    • An index of an nth '{' character must be inferior to the nth '}' character, etc.

If everything is ok, you have just to walk through the text and extract the substrings matching the text between nth '{' and nth '}'.

Ah, and don't use regular expressions here. Really, you don't need them in a such easy case, except to slow down everything and probably prevent you to validate the template, resulting sometimes in unexpected behavior.

MainMa
Thanks for your answer buddy. But I prefer to use Regular Expressions since that will minimize the processes. Thanks anyway buddy!
Abu Sithik
there's nothing wrong with using regular expressions here, your method looks like it's really over complicating things. cases like this are EXACTLY what regular expressions are for.
GSto
@GSto: I edited my answer to explain what's wrong with regular expressions here and why cases like this are EXACTLY what regular expressions are NOT for. Thus, I find @Gumbo solution quite clever, so I agree that this can be done his way.
MainMa
A: 
preg_match_all('/{.*}/U' , $string  , $a );

where $result will be

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(10) "{username}"
    [1]=>
    string(10) "{password}"
  }
}
Cedric
damn, codaddict and MainMa were too quick for me !
Cedric
and Sean Bright
Cedric