PDA

View Full Version : Getting variables from a string


filburt1
01-04-2003, 06:25 PM
Let's say I have a string that contains "This has a $var1 and $var2" (ignore escaping the $ for now). How can I find out what variable namess are in the string? I'm defining a variable name as everything from the leading $ to an illegal variable name character, including array braces ([]).

I know it probably involves regular expressions but I don't know anything about them.

filburt1
01-04-2003, 06:57 PM
Well after reading the docs they happened to have a regex string defining a variable, so I wrote this (ignore the junk about removing the $s):

function getvarnames($s, $includedollarsign = false)
// Returns all the variable names from $s, and, if $includedollarsign is true then
// they are all prefixed with a $.
{
preg_match_all("'\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'", $s, $a);
$s = array_unique($a);
if (!$includedollarsign) array_walk($a, "stripleadingcharall");
return $a;
}

Does it look like that works fine? It seems to in my test but I want to make sure it works for all conditions.

Xenon
01-04-2003, 09:39 PM
hmm, don't exactly know if it would work correctly, have you tried with $$vars ?

i think the expand function could also help you here....

filburt1
01-04-2003, 09:48 PM
Any examples? A slightly modified version of the above seems to be working fine for me...

Xenon
01-04-2003, 10:08 PM
sorry, meant strtok function....

function getvars($varstring) {
$vararray = array();
while($string = strtok($varstring," ") {
if (substr($string,0,1) == "\$") {
$vararray[] = $string
}
}
return $vararray;
}

think this should work

filburt1
01-04-2003, 10:16 PM
Problem is that could return just any things beginning with $. For example, it should work with a function like "$variable['index']" and return "$variable"

I'm pretty sure that the regex one is working so unless there's a more efficient way I think I'll keep that :)

Xenon
01-04-2003, 10:21 PM
a sorry, you are right then, your first sentence with including [] could be misunderstood (as i have done ;))