Jump to content

[SOLVED] Using ereg_replace MULTIPLE times?


gsaldutti

Recommended Posts

Hi all,

 

I included the entire code at the bottom of this post (not sure if I need to or not) but the part I'm having trouble with is the ereg_replace function seen in this part below.

 

$userResArray[$userCount]['row'] = ereg_replace('RecordPlaceHolder', $totalWinLossText, $userRow);
$userResArray[$userCount]['percentage'] = $successPercentage;
$userCount++;

 

This way above works fine, but what if I also want to do ANOTHER ereg_replace, in addition to the one that is already there.  I tried this way below but it only does the last (i.e. the second) ereg_replace...

 

$userResArray[$userCount]['row'] = ereg_replace('RecordPlaceHolder', $totalWinLossText, $userRow);
$userResArray[$userCount]['row'] = ereg_replace('name', 'name1', $userRow);
$userResArray[$userCount]['percentage'] = $successPercentage;
$userCount++;

 

 

Any help with how to do MULTIPLE ereg_replaces would be greatly appreciated. 

 

Also, as a side question (and please don't laugh at my inexperience  :)), but can someone please briefly explain what the "['row']" index does (i.e. where it has "$userResArray[$userCount]['row'] "), and explain it like I'm a five year old  ;D.    Is that index a default already built-in to PHP? Thanks! 

 

 

FULL CODE IF NECESSARY:

<?php
require_once("includes/session.php");
require_once("includes/connection.php");
require_once("includes/functions.php");

include_once("includes/form_functions.php");

$username="";
$password = "";


if(isset($_POST['submit'])) {
	$errors = array();

	$required_fields = array('username','password');
	$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
	$fields_with_lengths = array('username' => 30, 'password' => 30);
	$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));


	$username = trim(mysql_prep($_POST['username']));
	$password = trim(mysql_prep($_POST['password']));
	$hashed_password = sha1($password);



if ( empty($errors) ) {


	// check database to see if username and hashed password exist there
	$query = "SELECT userid, username ";
	$query .= "FROM users ";
	$query .= "WHERE username = '{$username}' ";
	$query .= "AND hashed_password = '{$hashed_password}' ";
	$query .= "LIMIT 1";
	$result_set = mysql_query($query);
	confirm_query($result_set);

	if (mysql_num_rows($result_set) > 0) {
		//username/password authenticated
		// and only 1 match

	 	$found_user = mysql_fetch_array($result_set);
		$_SESSION['userid'] = $found_user['userid'];
		$_SESSION['username'] = $found_user['username'];

	 	redirect_to("submit.php?userid={$_SESSION['userid']}");

	} else {
		// username/password combo was not found in database
		$message = "Username/password combination is incorrect.<br />
			Please make sure your caps lock key is off and try again.";

	}
}
}  

if(isset($_GET['logout']) && $_GET['logout'] == 1) {
	$message = "You are now logged out.";

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>GSFL 2008 - League Standings</title>
<link href="stylesheets/gsfl2008.css" media="all" rel="stylesheet" type="text/css" />
</head>
<div><img src="images/gsfllogo.gif"></div>

<div id="menu">
<p><a href="http://gdoot.com">Go to gdoot.com homepage</a></p>
<p><a href="rules.php">Read the Rules</a></p>
<p><a href="print.php" target="_blank">Printable Picks</a></p>
</div>



<div id="login">



<form action="index.php" method="post">
<table id="login">
<tr>
<td>Username:</td>
<td><input type="text" name="username" maxlength="30" value="<?php echo htmlentities($username); ?>" /></td>
</tr>
<tr>
<td>Password:</td>
    <td><input type="password" name="password" maxlength="30" value="<?php echo htmlentities($password); ?>" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Login to Submit Picks" class="submit" /></td>
    </tr>
    </table>
    </form>
  
  <?php if(!empty($message)) {
echo "<p class=\"message\">" . $message . "</p>";
}?>


</div>







<?php

function sortMultiArray($myRowArr, $assocOrNumericfieldIndex, $ascORdesc = 'asc'){
//Author: Dan
//Refer by whichever type of index you know is available, (associative or numeric)
//unset($myrow);
//strange I had to unset this before using it. it was appending blank rows at the end for
//some reason. actually doing the tradtional $myrow = array(); has the same effect
$retArr = array();
$rowCount = count($myRowArr);
if($rowCount){
	$arrKeys = array_keys($myRowArr[0]);
	for ($x=0;$x<$rowCount;$x++)
		{
		$colarr[$x] = $myRowArr[$x][$assocOrNumericfieldIndex];
		}
	//showArray($colarr);
	reset($arrKeys);
	//showArray($arrKeys);
	if(strtolower($ascORdesc) == 'asc'){
		asort($colarr); // Use arsort=DESC or asort=ASC
	}
	elseif(strtolower($ascORdesc) == 'desc'){
		arsort($colarr); // Use arsort=DESC or asort=ASC
	}

	$r = 0;
	for($sortedvar = reset($colarr); $sortedvar; $sortedvar= next($colarr))
	{
		$rank = key($colarr);
		for ($y=0;$y<count($myRowArr[0]);$y++)
		{
			$retArr[$r][$arrKeys[$y]] = $myRowArr[$rank][$arrKeys[$y]];
		}
		$r++;
	}
}
return($retArr);
}

echo "<p class=\"importantinfo\">Your \"pending\" picks will remain hidden until 12:59 PM on Sunday  (NOTE: You can see your \"pending\" picks if you login)</p>";

$outputStart = "<div id='standings'>
<table class=\"standings\" cellpadding='1' cellspacing='1'>
<tr>
<th class='name'>Player</th>
<th>Week 1</th>
<th>Week 2</th>
<th>Week 3</th>
<th>Week 4</th>
<th>Week 5</th>
<th>Week 6</th>
<th>Week 7</th>
<th>Week 8</th>
<th>Week 9</th>
<th>Week 10</th>
<th>Week 11</th>
<th>Week 12</th>
<th>Week 13</th>
<th>Week 14</th>
<th>Week 15</th>
<th>Week 16</th>
<th>Week 17</th>
</tr>";
$user_set = mysql_query("SELECT * FROM users", $connection);
if (!$user_set) {
die("Database query failed: " . mysql_error());
}

$userResArray = array();
$userCount = 0;

while ($users = mysql_fetch_array($user_set)) {

$userRow = "<tr><td class='name'>{$users["firstname"]}" . " " . "{$users["lastname"]}<br/><img src=\"http://gdoot.com/gsfl/images/user_{$users["userid"]}.jpg\" /> <span class=\"record\">RecordPlaceHolder</span></td>";
/*
$userRow .= '<td class="record">RecordPlaceHolder</td>';
*/
$day = date("w");
$time = time("Hi");
$wins = 0;
$losses = 0;
for($x = 1; $x <= 17; $x++){
$userRow .= '<td>';
$sql = "SELECT teamname, result
FROM teams, picks
WHERE picks.userid = '{$users["userid"]}'
AND picks.teamid = teams.teamid
AND picks.week = '$x' ";
$pick_set = mysql_query($sql, $connection);
if (!$pick_set) {
die("Database query failed: " . mysql_error());
}
if(mysql_num_rows($pick_set)){
$userRow .= "<table class='inset' cellspacing='0' cellpadding='1'>\n";
while ($picks = mysql_fetch_array($pick_set)) {

if ($picks['result'] == 'w') {
$userRow .= "<tr><td class='pickwin' rowspan='1'>{$picks['teamname']}</td>
</tr>\n";
$wins++;
}
elseif ($picks['result'] =='l') {
$userRow .= "<tr><td class='pickloss' rowspan='1'>{$picks['teamname']}</td>
</tr>\n";
$losses++;
}
elseif ((($picks['result'] == 'o') && ($day == 0)  && ($time > "1259")) || ($day == 1)) {
$userRow .= "<tr><td class='pickopen' rowspan='1'>{$picks['teamname']}</td>
</tr>\n";
}
else {
  $userRow .= "<tr><td class='pickopenhidden' rowspan='1'>&nbsp<span class=\"hide\">{$picks['teamname']}</span></td>
</tr>\n";
}
}
$userRow .= "</table>\n";
}
else  {
$userRow .= ' ';
}
$userRow .= '</td>';
}
$userRow .= "</tr>\n";

$totalPicks = $wins + $losses;
$successPercentage = 0;
$totalWinLossText = '';
if($totalPicks > 0){
$successPercentage = $wins / $totalPicks;
$totalWinLossText = " $wins - $losses";
}

$userResArray[$userCount]['row'] = ereg_replace('RecordPlaceHolder', $totalWinLossText, $userRow);
$userResArray[$userCount]['percentage'] = $successPercentage;
$userCount++;

}

$userResArraySorted = sortMultiArray($userResArray, 'percentage', 'desc');

$outputEnd = "</table>\n";
$outputEnd .= "</div>\n";

//Write the data table now
echo $outputStart;
for($x = 0; $x < count($userResArraySorted); $x++){
echo $userResArraySorted[$x]['row'];
}
echo $outputEnd;

?>


</body>
</html>
<?php
require_once("includes/footer.php");
?>

First of all, don't use ereg() or any of the POSIX Extended function because they're done with in PHP6 (except through PECL, but you probably won't be able to get it installed on most shared hosting plans).  Second of all, don't use ANY regex function for direct string replacing.  Check out the str_replace() function.

Ok, I'm using str_replace now (thanks for the tip), but I still run into the same problem where I can only do ONE str_replace.  If I list two in a row, it only does the second one.  I'm sure I'm missing something SUPER obvious, but I can't figure it out.

You can just pass an array in to str_replace, actually.

 

<?php
$find = array('RecordPlaceHolder', 'name');
$replace = array($totalWinLossText, 'name1');

$userResArray[$userCount]['row'] = str_replace($find, $replace, $userRow);
?>

 

Btw, it wasn't working before because you were modifying the $userRow variable both times.  After the first replace, $userRow is still unchanged, the data is just put into $userResArray[$userCount]['row'].  Get it?

It does make sense, thank you.  And using the arrays makes sense too, but it's not working for some reason.  I replaced my original code with the following code and nothing outputs now...

 

    $find = array('RecordPlaceHolder', 'name');
$replace = array($totalWinLossText, 'name1');
$userResArray[$userCount]['row'] = str_replace($find, $replace, $userRow);			
$userResArray[$userCount]['percentage'] = $successPercentage;
$userCount++;

<?php
$userRow = "Here's some totally interesting stuff about RecordPlaceHolder and their super special name";
$totalWinLossText = "nothing";
$find = array('RecordPlaceHolder', 'name');
$replace = array($totalWinLossText, 'name1');

$userResArray[$userCount]['row'] = str_replace($find, $replace, $userRow);
print_r($userResArray);
?>

 

 

Funny, because this works. >_>  Did you write this code yourself, btw?

I'm so sorry... I had ['row1'] written in my code later down the page by accident. i just caught it and when I changed it to ['row'] your code worked perfectly. Sorry about that.  Thank you very much for your help.  And as for your question about whether I wrote the code or not, I would say I wrote about half of it (and it took me a long time :) ).  Someone helped me with sorting function and basically wrote all the parts dealing with that.

Anyway, thanks again. I'm sure this is cake for you, but I'll get there some day :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.