Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop through string to find groups 1

Status
Not open for further replies.

ArtWerk

Programmer
Jul 31, 2006
66
US
I have a large string of text (variable) and i need to loop through it and count how many commas are in each group of the string. The string is in a variable ($string) and each group is surrounded in parenthesis (data, data, data).

so if
$string = (data, data, data), (data, data, data), (data, data), (data, data, data);
and
$x = 3;

I need to loop through this string and find all the groups that don't have $x items and add a blank one at the end to those without $x.

so the item: (data, data)
would need to be: (data, data, '')

I understand all i'd need to do is do a
str_replace(")",", '')", $string);

However, how do I ungroup those to see how many are in each row?

If it must be exploded into an array, that's fine, but I need it back in the string format to import into MySQL.

Thanks for the help.
 
try
Code:
explode("),",$string);
to give you an array of groups. remember to add the closing bracket and comma back in when you re-implode back to a string.
 
ok, i've started with that, but i'm not sure how to loop through each group item to add the necessary blank fields, for instance, in case the item has 3 in it, and it needs to have 5. So, I'd want to attach ", '', ''), " at the end. So far, I have:

Code:
$new_inserts = explode("),",$inserts);
$num_ins = count($new_inserts);
for($j=0;$j<=$num_ins;$j++){
	if(count(explode(",",$new_inserts[$j])) < $num_heads){
		$final_inserts .= $new_inserts[$j].", ''), ";
	}
}

I will more than likely only need to add 1 field at the end, but some CSV exports don't include anything for those fields if they're at the end of the row. i.e. if there's a blank field in the middle, they'll put "blah, '', blah", but at the end, it seems they just leave the blank ones off. So I'll need to always make sure each row has the same number of fields, otherwise i get an SQL insert error.

Only thing I could think of is to run through this process 2 or three times, but that seems a bit tedious. Any suggestions?
 
is this what you were intending?

Code:
<?
$string = "(data, data, data), (data, data, data), (data, data), (data, data, data)";
$x = 3;
echo normalise($string, $x);

function normalise($string, $num_records){
	//first get into an array
	$array = explode ("),", $string);
	
	//now walk through the array
	foreach ($array as $record){
		//quick way of determining how many commas there are
		$r = explode (",", $record);
	
		//calculate the difference between the number of data points and $x
		$diff = $num_records - count($r);
		
		//add in the right number of commas
		if ($diff > 0){
			for ($i=0; $i<$diff; $i++) {
				$r[]="";
			}
		}
		//create a new array element with the fixed record and replace terminating bracket
		$newarray [] = implode (",", $r) . ")";
	
	}
	$newstring = implode (",", $newarray);
	//get rid of the trailing bracket
	return substr($newstring,0,strlen($newstring)-1);
}

?>
 
Wow. Your method works great! I think I still have a comma at the end, but no problem getting rid of that. I was using this (for rows that were short only 1 field):
Code:
$new_inserts = explode("),",$inserts);
$num_ins = count($new_inserts);
for($j=0;$j<=$num_ins;$j++){
	$insert_row = str_replace("('","(NULL, '",$new_inserts[$j]);
	$insert_row = str_replace(")","",$insert_row);
	if(count(explode(",",$insert_row)) < $num_heads){
		$final_inserts .= $insert_row.", ''), ";
	} else {
		$final_inserts .= $insert_row."), ";
	}
}

$final_inserts = trim($final_inserts);
$final_inserts = str_replace(", , ''),","",$final_inserts);

In mine, I'm adding a field to the front of all fields "(NULL, ". Where would I do that in your function?

Thanks again!
 
i'm not sure whether this is quite what you meant. it first works out how many fields to add in at the end, and does so. it then adds a NULL as the first field. so you are left with (num_records + 1) records.

there may be a better way of pushing an array element onto the front of an array (rather than the end) but array_merge is typically what i use for this.

Code:
<?
$string = "(data, data, data), (data, data, data), (data, data), (data, data, data)";
$x = 3;
echo normalise($string, $x);

function normalise($string, $num_records){
    //first get into an array
    $array = explode ("),", $string);
    
    //now walk through the array
    foreach ($array as $record){
		//remove first bracket
		$record = ltrim($record, "(, ");
        //quick way of determining how many commas there are
        $r = explode (",", $record);
    
        //calculate the difference between the number of data points and $x
        $diff = $num_records - count($r);
        
        //add in the right number of dummy elements
        if ($diff > 0){
            for ($i=0; $i<$diff; $i++) {
                $r[]="";
            }
        }
		//add a NULL element as first array element
		$r = array_merge(array("NULL"), $r);
        //create a new array element with the fixed record and replace terminating bracket
        $newarray [] = "(" . implode (",", $r) . ")";
    
    }
    $newstring = implode (",", $newarray);
    //get rid of the trailing bracket
    return substr($newstring,0,strlen($newstring)-1);
}

?>

i do not get the trailing comma in either of my versions. i guess we are using a different input string. preg_match() may be a neater way of getting the internal contents of the bracketed data but i am not sure that it will be as rapid.

[/code]
 
Hmm.. It seems to work for the most part, however I have one file that the last record gets the blank field inserted after the ), so I end up with:

...blah, blah),'';

This is the function as I have it:
Code:
function normalise($string, $num_records){
    //first get into an array
    $array = explode ("),", $string);
    
    //now walk through the array
    foreach ($array as $record){
        //remove first bracket
        $record = ltrim($record, "(, ");
        //quick way of determining how many commas there are
        $r = explode (",", $record);
    
        //calculate the difference between the number of data points and $x
        $diff = $num_records - count($r);
        
        //add in the right number of dummy elements
        if ($diff > 0){
            for ($i=0; $i<$diff; $i++) {
                $r[]="''";
            }
        }
        //add a NULL element as first array element
        $r = array_merge(array("NULL"), $r);
        //create a new array element with the fixed record and replace terminating bracket
        $newarray [] = "(" . implode (",", $r) . ")";
    
    }
    $newstring = implode (",", $newarray);
    //get rid of the trailing bracket
    return substr($newstring,0,strlen($newstring)-1);
}
 
ok, i think i figured out the problem. I removed the last ")" when it removes the first "(". That did the trick.

Thanks again!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top