PHP - Search And Replace, Then Do Math.
I can' t even get the simple str_replace to work. I got....
$rslt = $client->getTodaySubIDStats($key, $sub_id); $rslt = str_replace("EARNINGS",'',$rslt); $rslt = str_replace("Array","",$rslt); $rslt = str_replace("\r","",$rslt); $rslt = str_replace("\n","",$rslt); $rslt = str_replace("\t","",$rslt); print_r($rslt); which spits out.... Code: [Select] Array ( [0] => Array ( [EARNINGS] => $100.40 [CLICKS] => 1301 [LEADS] => 100 [SUB_ID] => yacker [EPC] => $0.11 ) ) I would like to have every thing removed except the '$100.40' (The number is always changing). Then remove the $ and do math 100.40*.40, so in the end, all it spits out is 40.16 and always only have two digits after the period. Similar TutorialsThe situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.
For example:
<?php $str = 'some blob ~abc~ followed by ~def~'; $arr_orig = array( '~abc~', '~def~' ); $arr_new = array( 'value~def~', 'blah' ); echo str_replace( $arr_orig, $arr_new, $str ); ?>This will echo: some blob valueblah followed by blah But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need. I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!) I have a number of records of the html sections of a series of Google Earth placemarks that I managed to extract from the raw kml file. The purpose of the exersize was to then use the simplehtmldom.php api to extract the DATA from the raw html code. Some of the process is going well... and some is NOT. I have found that if I modify the raw html code by entering ID attributes into the html code the simplehtmldom api has an easy time identifying the desired data, and the data can be far 'cleaner' by entering an id attribute as 'close' to the data as possible. But doing a php text search and replace often requires finding a 'unique' identifyable portion of the html code and THEN placing the 'id' attribute in a nearby html tag because the desired data is nested inside a non-unique tag. As in I can identify a SPECIFIC <td> tag section where the data i desire is located but the data is nested inside a <font> tag inside the <td> cluster. Hence my problem... If I do a search in the following code... Code: [Select] <td><b><font size="+2" color="#FF0000">Neighborhood:</font> <font size="+2" color="#0000FF">City of Sidney</font></b></td> I can locate the 'Neighborhood:' string because it is unique in the whole html code. Then by some charcter counting I am desiring to put my 'id' attribute in the NEXT font tag because it surrounds the desired data the 'City of Sidney'... as in... Code: [Select] <td><b><font size="+2" color="#FF0000">Neighborhood:</font> <font id="neighborhood" size="+2" color="#0000FF">City of Sidney</font></b></td> With this modification the desired data is easily found and cleanly produced. But the html code while all operating correctly in a web page is not all identicle from a 'whitespace' point of view AND thus my problem. If I search the following code... Code: [Select] <td> <b><font size="+2" color="#FF0000">Neighboorhood:</font> <font size="+2" color="#0000FF">Greenacre</font></b> </td> While being identical as far as html is concerned if I search this code for the 'Neighboorhood:' identifier I find it... but then attempting to place the id tag into the NEXT font tag is being problematic. What i seem to need is a function that once the 'Neighboorhood:' string position is identied and noted in the whole of the html code, to FIND and modify the NEXT occurance of a font tag no matter what whitespace (or special charachters) may be occuring. Any suggestions?? eatc7402 $file=str_replace("{title2}",$line['title'],$file); $file['title2'] = trim(preg_replace('/[^\w\d]+/', ' ', $file['title2'])); $file['title2'] = str_replace(' ', '-', $file['title2']); The first line does what it should do, have {title2} in the template generate the page title. The next two lines don't do the replacing. Hi everyone!! I just started learning PHP two weeks ago and I hope someone can help me!! I need to do a find and replace on a string, and each replace needs to have an unique id, and if that unique id exists in a table then return the value on the table. Make sense? So like "find all the Xs in the string, replace with "X1, X2, X3...", then if "X3' exists on TableB, return value "X3 is on the table and has a value of Y3". I actually got this to work already but it takes a long time to do it so I'm hoping someone could give me some advice on how to make it more EFFICIENT: // PART ONE, find all "X" and replace with unique_id for ($count = 1; $count <= strlen($string); $count++) // do this loop as many times as there are characters in $string { $unique_id = "replacement_" . $count; // give each replacement an unique id (replacement_1, replacement_2, replacement_3, etc..) $string = preg_replace("X", $unique_id, $string , 1); // find X and replace it with the $unique_id in $string, and only do this ONCE } $count_replacements = substr_count($string,"replacement_"); // count how many replacements occured in total // PART TWO, find all unique_ids in tableB and echo the unique_id_value for ($count = 1; $count <= $count_replacements; $count++) // do this loop as many times as there were replacements { $unique_id = "replacement_" . $count; // set the unique_id of each replacement $show_tableB = mysqli_query($link, 'SELECT * FROM tableB'); // select the unique_ids and the unique_id_values in TableB while ($row = mysqli_fetch_array($show_tableB)) { $tableBs[] = array('unique_id' => $row['unique_id'], 'unique_id_value' => $row['unique_id_value']); } foreach($tableBs as $tableB): // for each entry in TableB, if the unique_id in TableB matches the unique_id of the replacement, return the unique_id_value if ($tableB['unique_id'] == $unique_id) { echo $unique_id . " is on TableB and it has a value of ". $tableB['unique_id_value'] } endforeach; } The problem with this is: its not very efficient. If $string has 500 charachters, it does the "PART ONE" 500 times. Then, say it found 300 Xs, it does "PART TWO" 300 more times. And every time it does "PART TWO", it checks all entries in TableB (which could be 200 or more). So, that's it. Anyone has a better idea of how to do this?? Thanks!!!! Hi i wrote a find and replace code but my code replace last value of array and skip the first, second.... values in the array. Please give me an idea because i stack with this code. Regards $KeyWord = explode("\n", $RowGetWords['KEYWORDS']); $Replace = explode("\n", $RowGetWords['ReplaceTo']); for($i=0; $i<count($KeyWord); $i++){ $pattern = $KeyWord[$i]; $replace = "<a href=\"" .$URL. "\" target=\"_blank\" >" .$Replace[$i]. "</a>"; $html = str_replace($pattern, $replace, $Row['MessageBody']); } The result pages is supposed to have pagination like google help me please
is there a math function that give you an integer value when u divide 2 numbers? ie in 7/3 i just want 2 as a result not floating number. thanks in advance. Hi, I am TheMeq. I am currently developing a Text-Based MMORPG in PHP/MySQL. I have quite alot of the code laid down, its just this bit that is starting to throw me a bit. I've been working on it since 8am this morning.. it is now 4:30pm and i think it's nearly there. It's just not working the way I would like. So if I was to ask for help, should I just post what code I have? I'm trying to make a script to check a files date time and if its under so many seconds long the page will refresh. here is what I've got. I've been testing the output of the date() functions but when i do the math all i get is a 0. where did i go wrong? is it just i can't do math with dates? Thanks in advanced. Code: [Select] <html><head> <meta http-Equiv="Cache-Control" Content="no-cache"> <meta http-Equiv="Pragma" Content="no-cache"> <meta http-Equiv="Expires" Content="0"> <? $proFile = "profilePics/profile.jpg"; //if ( date ("m d Y H:i:s.") - date ("m d Y H:i:s.", filemtime($proFile)) <= 00 00 0000 00:00:04 ){ //this is where the magic should happen. //echo "<meta http-equiv="refresh" content='4'>"; } ?> </head> <? echo date ("m d Y H:i:s."); echo "<br>"; echo date ("m d Y H:i:s.", filemtime($proFile)); echo "<br>"; echo date ("m d Y H:i:s.") - date ("m d Y H:i:s.", filemtime($proFile)); //only outputs 0 ?> Trying to get the percentage of rent for a property in php. Im completely lost .... Code: [Select] <?php $purchase = 44000; $rent = 9860; $percent = $purchase * $rent; //this is wrong, it returns 4.3 but should be over 18 echo "Percentage is {$percent}%"; ?> Hello Everyone, I'm a newbie trying to improve my script below. The script works fine but I would like to add the 3 radio buttons computations enhancements Ergo, if a user chooses 'Matte Paper" a 10% would be added to the Price Quote result. If a user chooses ' Gloss Paper, a 10% would be added to the Price Quote result. If a user chooses 'Canvas" , a 20 % would be added to the Price Quote result. If someone could assist with the math or post me a helpful link it would be greatly appreciated. Thank you. Paul from Melbourne, Australia. <div style="border:dashed 1px; width:570px;"> <form method="post" action="<?php echo $_SERVER['php_SELF'];?>"> <p> 1. Enter the size (100w.x180h. cm) you want your picture printed: Width <input type="text" name="width" size="1" maxlength="3" value="0" onFocus="this.value=''; this.style.color='#ff0000';"> Height <input type="text" name="height" size="1" value="0" maxlength="3" value="0" onFocus="this.value=''; this.style.color='#ff0000';"> </p> <p> 2. Choose the printing material for your pictu <input type="radio" value="cms in Matte paper" name="material" size="3" maxlength="3" /> Matte Paper <input type="radio" value="cms in Gloss Paper:" name="material" size="3" maxlength="3" /> Gloss Paper <input type="radio" value="cms in Canvas:" name="material" size="3" maxlength="3" /> Canvas </p> <p> 3. Submit your info for our Price Quote below : <input type="submit" name="submit" value="Submit" /> or: <input type="submit" name="clear" value="Reset" /> </p> <p> 5. Our Price Quote to print your artwork sized: <?php $width = $_POST['width']; /* if artwork wider than 101 cm no quote, exits*/ if ($width >=101) {echo "Error!"; exit ;} $height = $_POST['height']; /* if artwork higher than 181 cm no quote, script exits */ if ($height >=181) {echo "Error!"; exit ;} $measurement = $_POST['measurement']; $material = $_POST['material']; $result = $width * $height; echo " $width x $height $material is: "; echo "$".number_format($result,2). "" ; ?> </p> </form> </div> Hi guys. I'm using php to randomly generate a simple math verification question. But, I'm having a hard time validating the input. Can someone please tell me what I'm doing wrong? Thank you } else if(trim($verify) != $_SESSION['UserData']['Math'][0]+$_SESSION['UserData']['Math'][1]){ $error = '<div class="error_message">Attention! The verification number you entered is incorrect.</div>'; } <?php echo "<span class='label'><span class='required'>*</span>What is ".$_SESSION['UserData']['Math'][0]." + ".$_SESSION['UserData']['Math'][1]."?</span> "; ?> <input name="verify" type="text" id="verify" size="3" value="<?=$verify;?>" /><br /><br /> I am trying to create a math equation inside a variable but I am struggling to achieve the desired result. On one php page I have this:
$x = "date('Y')"; On my main page I have linked to the above and also $description but the result I am getting is: In this classic lecture which was delivered over date('Y') - 1989 years ago,
I want to create a variable so I don't need to go back every year and change the description. Is this possible? Robert
Having to go into somebody else's code yet again! Gah! Originally the totaling page just subtracted a flat discount. But now the client wants to be able to subtract percentage discounts and 'per item' discounts. In the discount table I added a field to determine whether the discount chosen is to be applied as flat off total, flat per item, % off total, and % off each item. I also entered a field that can have a class id, in case this discount is only for that class. (the intention being that otherwise the discount is on anything) I've got a session variable that generates something like : Array ( [217] => 1 [215] => 2 ) meaning 1 person in class #217, and 2 people in class 215. $_SESSION['s_to_be_added'] = array_filter($_POST['participantqty']); Then on the page I'm concerned with, I've been trying to write the script. I know I still need some math stuff figured out But how do I take the array, do the math, and then generate an overall cost for the whole thing? and this is just the discounting? I don't even have a clue how to work in delimiting it if there's a class id.. did any of that make sense? Code: [Select] <?php // the above is the array I want to use to $passed_array = array_filter($_SESSION['s_to_be_added']); // this is the discount 'code' the user entered. $discount = mysql_escape_string($_POST['discount']); // just a donation added after everything. $donation = mysql_escape_string($_POST['donation']); // finding the discount that matches the discount 'code' entered. $query_selectAllItems_events = "SELECT discount_amount,discount_type,workshop_link_1 FROM tbl_discount where discount_value = '$discount'"; $result_all_events = mysql_query($query_selectAllItems_events); $numRows_all_events = mysql_num_rows($result_all_events); $num=mysql_num_rows($result_all_events); $z_row = mysql_fetch_array($result_all_events); // this is just a number: 1, 20, 90 etc. $discount_amount = $z_row['discount_amount']; /*this is 1,2,3,4 - for each type of discount 1- flat 2- flat per item 3- discount on all, 4- discount per item */ $discount_type = $z_row['discount_type']; // the workshop id if the discount is onlyh for this workshop $discount_link_1 = $z_row['workshop_link_1']; // just a description $discount_name = $z_row['discount_name']; if ($discount_type ==1) { /* flat discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==2)) { /* discount per item total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==3)) { /* percentage discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } elseif ($discount_type ==4)) { /* percentage discount per item here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } ?> Website: http://novacms.vacau.com/index.php I'm trying to make a calculator for this game I play, it's fully developed, but with one bug. It doesn't do the math right. $goal = The amount of EXP (Experience Points) someone wants to get $exp = The amount of EXP they currently have $npcs_exp["exp"] = The amount of EXP the monster has But, when they enter in the information, the calculation is all screwed up. When I do it, it seems to give me the same number EACH time. The part where the calculation "goes down". Remember, I'm trying to see how many times you need to kill a NPC to achieve your goal. //math $npc_exp_extract = mysql_query("SELECT exp FROM npcs WHERE name='$npc'"); $npcs_exp = mysql_fetch_assoc($npc_exp_extract); $amount = $goal / $npcs_exp["exp"]; Full code: <?php $exp = $_POST["exp"]; $npc = $_POST["npc"]; $goal = $_POST["goal"]; mysql_connect("removed", "removed", "removed"); mysql_select_db("a2248602_npcs"); if(!$goal || !$npc || !$exp) { echo "<center><form action='index.php' method='POST'>GOAL: <input type='text' name='goal'> Current XP: <input type='text' name='exp'>"; echo "NPC: <select name='npc'>"; $npc_extract = mysql_query("SELECT * FROM npcs"); while($npcs = mysql_fetch_assoc($npc_extract)) { echo "<option name='". $npcs['name'] ."'>". $npcs['name'] ."</option>"; } echo "</select> <input type='submit'></form></center>"; } else { //math $npc_exp_extract = mysql_query("SELECT exp FROM npcs WHERE name='$npc'"); $npcs_exp = mysql_fetch_assoc($npc_exp_extract); $amount = $goal / $npcs_exp["exp"]; if($amount=="1") { echo "You will need to kill a <b/>". $npc ."</b> <b>". $amount ."</b> more time. You earn ". $npcs_exp["exp"] ." XP for each kill from this NPC. | <a href='index.php'>Do another</a><br/><br/>"; } else { echo "You will need to kill a <b/>". $npc ."</b> <b>". $amount ."</b> more times. You earn ". $npcs_exp["exp"] ." XP for each kill from this NPC. | <a href='index.php'>Do another</a><br/><br/>"; } } echo "<center>Made by Zaros from <a href='creation-x.net'>Creation-X</a></center>"; ?> Mod edit: DB credentials removed. The title may not fit but only thing i could think of. I am pulling data from MSSQL database table.... I need everything from that table but i need to do some basic math funcitons to the resulting data. So the quesiton is should i do the math for this in the SQL query if so how do i pull all fields and do the math in an effcient way. Or should i let php do the math for me after i get all the data i need. If it is better to use php how can i do this in a while loop and get the math result and not a printed equation. Just looking for a few pointers never had to do math before with php question here... say we have a string coming from a form, already verified that its numeric/mathmatical(+-*/) how can we then process that into an answer without using eval? Code: [Select] $string='1+2*3'; echo process($string); #7 Quote If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP This topic has been moved to PHP Math Help. http://www.phpfreaks.com/forums/index.php?topic=350528.0 Code: [Select] if ($user['amount'] >= 15.00){ $user['max_stars'] = 3; } Ok and Code: [Select] if ($user['amount'] >= 20.00){ $user['max_stars'] = 4; }How can I write a function that will loop through the 15,20,25,30,35, all the way up to 600$ or if the max_Stars get's up to 80? I really don't want to have 80 if functions in my code :\ I am doing some simple math and it is spitting out very odd results. //First Loop to get the values $get_values = mysql_query("SELECT * FROM table"); while($values = mysql_fetch_array)){ $value_one += $values[value_one]; $value_two += $values[value_two]; } $difference = $value_one - $value_two; echo"$value_one - $value_two = $difference; The database field types are DECIMAL(10,2). The output of the individual values is echoing the correct 0.00 format but after it loops for awhile the difference seems to come out differently. and have close to 5 or 6 places after the decimal. if i echo the values as it is looping and adding them it seems to not be adding correctly either. What am I doing wrong? |