Parsing variable names from strings

Discussion in 'PHP' started by meloncreative, May 24, 2010.

  1. #1
    Hey all

    So I have a function I am writing that outputs a mysql query. The function is to be used for lots of separate tables, and therefore I decided to have a variable to hold any conditions.

    Sometimes the condition variable needs to hold a variable name, so I have made it parse the variable and put that in the query, but because I had to use preg_replace_callback it seems to not like grabbing the value for the variable because it is within the callback function.

    	function getLimitedList($form, $offset, $limit) {
    	$form_info = $this->getFormInfo($form);
    	$table = $form_info['fgf_dbname'];
    	$parent_form = $form_info['fgf_parent'];
    	$parent_info = $this->getFormInfo($parent_form);
    	if (!empty($parent_info['fgf_dbname'])) {
    		$parent_table = ",".$parent_info['fgf_dbname'];
    	}
    	$condition = $form_info['fgf_condition'];
    
    	echo "<br>$condition";
    	echo "<br>";
    	// the callback function
    	function parse_vars($matches) {
    		return $$matches[1];
    	}
    	echo preg_replace_callback(
    	            "/[\$]([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/",
    	            "parse_vars",
    	            $condition);
    	
    	$result = $this->query("SELECT * FROM $table $condition LIMIT $offset, $limit");
    	
    	return $result;
    }
    PHP:
    This outputs

    WHERE formgen_conffields.fgc_parentform = (SELECT fgf_id FROM formgen_forms WHERE fgf_cleanname = '$table')
    WHERE formgen_conffields.fgc_parentform = (SELECT fgf_id FROM formgen_forms WHERE fgf_cleanname = '') 
    PHP:
    Top line being without the parsing, and the 2nd line with, so it figures out the variable name ok, but just will not get the value for it.

    Tried making the $table variable global, no joy, yet when I declare it as a value within the callback function it works

    Any ideas what I am doing wrong?
     
    meloncreative, May 24, 2010 IP
  2. meloncreative

    meloncreative Peon

    Messages:
    37
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    nevermind, figured it out myself. Because it was a nested function, I had to make the variable global for the parent and child function :)
     
    meloncreative, May 24, 2010 IP