PHP - Preg_replace Thousands Of Arrays From Table
Below is the code I have so far for only 2 terms with '$word" being the keyword of the site and all the other words are suppose to be linked if they appear in the text. Okay I have thousands of different possible words from the same table. In the table 'word' is the term to be defined and 'definition' is the main content. I want a code that recognizes any word that is listed in my table and replaces it. <?php $find2 = array ('/$word/i', '/bond/i'); $replace2 = array ('<a href=http://www.subjectmoney.com/definitiondisplay.php?word=$word><b>$word</b></a>', '<a href=http://www.subjectmoney.com/definitiondisplay.php?word=Bond>bond</a>'); Echo preg_replace ($find2, $replace2, $definition); ?> Similar TutorialsHello,
Anyone can suggest me what is the best way to update table records. I'm kinda scared to make an update on a table because it may damage the system and I am not really good on SQL commands.
Right now I just made a process on PHP to update table records. It does update email records on but it stop because of the limit of loading the page. Is there anyway accurately update all the data of the table.
Here is what I want to achieve.
I have a table with an "email" field on it, those email data from "email" field on tb_one must be change to cID records base on tb_two.
tb_one
Field =
- id
- email
- etc.
tb_two
Field =
- id
- email (same as on tb_one)
- cID
Hello,
Any ideas why server resources not exhausted on the code below, when my.cnf and php.ini are both set to use half the resources each? PHP & MySQL will both utilize all allotted resources on other scripts, so it's not a tuning problem. There is no script-side tuning.
The bottleneck: pdo select as shown below
foreach($bigList as $listObject) { $sql = $dbl->prepare("SELECT * FROM fewMillionRows WHERE indexedCol1=:indexedCol1 AND indexedCol2=:indexedCol2 AND indexedCol3=:indexedCol3 AND indexedCol4=:indexedCol4 LIMIT 1"); $sql->execute($preparedValues); $return = $sql->fetchAll(PDO::FETCH_ASSOC); }On a dedicated server with 8GB RAM, the server uses >5% cpu/ram but takes a long time to finish the script. Second Question What are some alternative designs? Because the column values all happen to be alphanumeric, I could select the entire table and store it in an array. Accessing the keys like so: indexedCol1indexedCol2indexedCol3indexedCol4. Results: MyISAM - Select Whole Table: 30 seconds MyISAM – Select Individual Rows (10k times) – 68 seconds InnoDB – Select Whole Table: 30 seconds InnoDB – Select Individual Rows (10k times) – 131 seconds I am surprised it takes so long to select a whole table. The server resources use 1% for about 20 seconds, then cpu/ram jump to 30%+ for about 10 seconds. This is still drastically faster than individual selects. In this instance, $bigList is over 500k items. At 68 seconds per 10k rows it’s absurdly long. Building an array with key/values is the only realistic way I currently know of, but I suspect there is a much better way of doing this. As far as I know, I cannot do a select like so: SELECT * FROM t1 WHERE (column1,column2,column3) IN ((val1, val2,val3), (val4, val5,val6)) There is no way to determine whether a row was found for each entry as far as I know. Given the following query,
SELECT t1.a, t1.b, t2.c FROM t1 INNER JOIN t2 ON t2.id=t1.t2_id WHERE t1.pk=123;I get the following three records: array( array('a'=>1,'b'=>2,'c'=>4), array('a'=>1,'b'=>2,'c'=>5), array('a'=>1,'b'=>2,'c'=>8) )What would be the best way to get just one record such as the following? array('a'=>1,'b'=>2, 'c'=>array(4,5,8))My thoughts were to use MySQL's GROUP_CONCAT, and then use implode() to turn it into an array, but didn't know if there was a better way. Thanks Hi
I have a table i populate from database (upon a parameter the user insert and with PHP $_GET i take this value and populate the table accordint to if). After I allow the user to add or edit data in rows by using jquery. The last part I do is to want to save the changes back to database using PHP. The jquery i use suppose to serve different tables. So its written in a way that get the table structure and add rows upon it. In this example I put it in the index page Everything works fine,but I cant build the array from the added rows. My variables in the php part got null values (although in debug mode I see that $_POST... store data in the array What do I miss here? Thanks here is my php+ html part of index,php <?php require_once("../xxx/Includes/GlDbOra.php"); if(isset($_POST['submit_btn'])) { $catalog_id=$_GET['catalog_id']; $tableRow = $_POST['tableRow']; foreach ($tableRow as $row) { $item_id=$row['ITEM_ID']; $item_name=$row['ITEM_NAME']; $userid=$_SESSION['userid']; $program='PHP'; $stid=DBOracle::getInstance()->insert_items($catalog_id, $item_id, $item_name, $userid, $program); } } if (!empty($_GET['catalog_id'])) { $catalog_id=trim($_GET['catalog_id']); $catalog_id_desc=$_GET['catalog_id_desc']; $stid=DBOracle::getInstance()->get_items($catalog_id); } ?> <html> <head> <meta charset="UTF-8"> <title>Items</title> <script type="text/javascript" src="../../Bundles/php-ajax/jquery-3.5.1.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script type="text/javascript" src="../../Bundles/bootstrap-4.5.0-dist/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link href="../../Bundles/bootstrap-4.5.0-dist/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <link href="../xxx/css/global_style.css" type="text/css" rel="stylesheet" madia="all"/> </head> <body> <div id="page-wrap"> <section id="main-content"> <div id="guts"> <span style="clear: both; float: left; margin-left: 5%;"> <form id="param_form" name="populate_table" method="GET" action="index.php"> <label for="catalog_id">Catalog Id</label> <input type="text" name="catalog_id" class="catalog_id" id="left_radius_textbox" value=" <?php echo htmlspecialchars($catalog_id, ENT_QUOTES); ?>" placeholder="<?php echo catalog_id; ?>"/> <input type="text" name="catalog_id_desc" class="catalog_id_desc" id="right_radius_textbox" value=" <?php echo htmlspecialchars($catalog_id_desc, ENT_QUOTES); ?>" readonly /> <button class="load_form"><span class="glyphicon glyphicon-refresh"></span> Get Data</button> </form> </span> <br> <div class="container"> <div class="row"> <div class="panel panel-primary filterable"> <div class="panel-heading"> <h3 class="panel-title">Items</h3> <div class="pull-right"> <button class="btn btn-default btn-xs btn-filter"><span class="glyphicon glyphicon-filter"></span> Filter</button> </div> </div> <form id="form" name="form1" method="POST" action=""> <table class="table table-fixed" id="tab_logic"> <thead> <tr class="filters" id ="table_header_2_btn"> <th class="col-xs-2"><input type="text" name="tableRow[0]['ITEM_ID']" value="" placeholder="Item Id" disabled></th> <th class="col-xs-6"><input type="text" name="tableRow[0]['ITEM_NAME']" value="" placeholder="Description" disabled></th> <th class="col-xs-4"></th> </tr> </thead> <tbody> <?php $catalog_id=$_GET['catalog_id']; $count=0; while ($row= oci_fetch_array($stid, OCI_ASSOC)): echo "<tr>"; echo "<td class=".'"col-xs-2"><input name="tableRow['.$count.']['."'ITEM_ID']".'"'.' value="'.htmlspecialchars($row['ITEM_ID'], ENT_QUOTES).'" style='."'border:none;".'></td>"'; echo "<td class=".'"col-xs-6"><input name="tableRow['.$count.']['."'ITEM_NAME']".'">'.htmlspecialchars($row['ITEM_NAME'], ENT_QUOTES)."</td>"; $count++; ?> <td class="col-xs-4"> <a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a> <a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a> <a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a> </td> <?php echo "</tr>\n"; endwhile; oci_free_statement($stid); oci_close($con); ?> </tbody> <tr> <button class="regular_button" id="add-new"><span class="glyphicon glyphicon-plus"></span> Add Rows</button> <td><input type="submit" name="submit_btn" value="Submit"></td> </tr> </table> </form> </div> </div> </div> </div> </section> </div> <script> </script> </body> </html> and here is the jquery part in the index.php (that in between the <script></script>) $(document.body).on('click', '#add-new', function() { $('[data-toggle="tooltip"]').tooltip(); var actions = $("#tab_logic td:last-child").html(); $(this).attr("disabled", "disabled"); var index = $("#tab_logic tbody tr:last-child").index(); var newRow = $("<tr>"); var cols = ""; var element_string=''; var table_structure = $('#table_header_2_btn')[0].innerHTML; table_structure=$.trim(table_structure); var arrStr = table_structure.split(/\n/g); for(var i=0; i<arrStr.length-1; i++) { arrStr[i] =$.trim(arrStr[i]); element_string=arrStr[i]; if (element_string.indexOf('<th')!=-1) { var n=element_string.indexOf('<th'); element_string='<td'+ element_string.substr(n+3); var n=element_string.indexOf('[0]'); element_string= element_string.substr(0,n)+'['+index+']'+element_string.substr(n+3); } if (element_string.indexOf('placeholder=')!=-1) { var n=element_string.indexOf('placeholder='); element_string=element_string.substr(0,n-1); element_string=element_string + '</td>'; } cols+=element_string; } cols+='<td class="col-xs-4">' + actions + '</td>' cols +='</tr>'; newRow.append(cols); $('#tab_logic').append(newRow); $("#tab_logic tbody tr").eq(index + 1).find(".add, .edit").toggle(); $('[data-toggle="tooltip"]').tooltip(); }); $(document).on("click", ".add", function() { var empty = false; var input = $(this).parents("tr").find('input[type="text"]'); input.each(function() { if(!$(this).val()) { $(this).addClass("error"); empty = true; } else { $(this).removeClass("error"); } }); $(this).parents("tr").find(".error").first().focus(); if(!empty) { input.each(function() { // $(this).parent("td").html($(this).val()); }); $(this).parents("tr").find(".add, .edit").toggle(); $("#add-new").removeAttr("disabled"); } }); $(document).on("click", ".edit", function() { $(this).parents("tr").find("td:not(:last-child)").each(function() { $(this).html('<input type="text" value="' + $(this).text() + '">'); }); $(this).parents("tr").find(".add, .edit").toggle(); $("#add-new").attr("disabled", "disabled"); }); $(document).on("click", ".delete", function() { $(this).parents("tr").remove(); $("#add-new").removeAttr("disabled"); });
In my form I have this: Code: [Select] <div class="confSub {conferences.confClass}"> <div> <input type="hidden" name="confPK" value="{conferences.confPK}"> <label>Conference Attended:</label><input size="85" name="conference[{conferences.confCounter}]" type="text" value="{conferences.conference}"/> <label>Date:</label><input size="20" name="confDate[{conferences.confCounter}]" type="text" value="{conferences.confDate}"/> <span class="example left"> ( YYYY-MM-DD )</span> <label class="fullLabel clearfix">Description and Benefit to the University:</label> <textarea name="confDesc[{conferences.confCounter}]" cols="90" rows="5">{conferences.confDesc}</textarea> <input class="checkbox clearfix" name="confPres[{conferences.confCounter}]" value="yes" type="checkbox" {conferences.checkedConf}/> <label class="midLabel">Conference Presentation?</label> <label class="clearfix">Title of Presentation:</label> <input class="pushLeft" size="85" name="confPresTitle[{conferences.confCounter}]" type="text" value="{conferences.ConfPresTitle}"/> </div> </div> I need to take the values of the same index for eachof five arrays ($_POST['conference'], $_POST['confDate'], $_POST['confDesc'], etc...) and insert/update them into a mysql table. So conference[0], confDate[0], confDesc[0], confPres[0], and confPresTitle[0] all need to go into the same index of their respective fields in the DB table. If it was one array I could just do something like: foreach($_POST['conference'] as $conference) { // Update Conference $degreeQuery = "UPDATE CONFERENCES SET Conference = '".$conference."', StaffPK1 = '".$getPK1."' WHERE ConferencePK1 ='".$confID."'"; $degreeQuery = mysql_query($degreeQuery); } I'm having trouble with how to add a value from each array into the sql table. I could do it through a different foreach loop for each array and iterate through all foreach loops with another loop, but that doesn't seem very efficient. I'd like to do it with one sql statement for each set of "conference" data. Thanks in advance, Shannon for starters, i am a complete beginner at PHP, so i know almost nothing.
so, the basic outline is that i am required to create a table with 2 columns, and use PHP where i can
so the first set of code lays down the table and the ability to type in text of "name" and "surname". ----i think this "input" is HTML, yes?? is there a way to enter it as PHP?
<table border=\"2\"> <tr><th><b>Requirements</b></th><th><b>Selections</b></th></tr> <tr><td>Name</td><td><input type="text" name="name"/></td></tr> <tr><td>Surname</td><td><input type="text" name="surname"/></td></tr>so, for this next section, adding on is the part for "age". i want this to appear as a dropdown selection. i've written PHP where possible, however this does not work when opening the file in a browser. it simply leaves a blank dropdown menu with no options. ???? <tr><td>Age</td><td><select> <?php for ($num=11; $num<=22; $num++){ echo '<option>' .$num. '</option>'; } ?> </select>lastly, i have the part for "activity choice". this again i believe i wrote the radio buttons in HTML??? am i able to write this as PHP???? <tr><td>Activity Choice</td><td><input type="radio" name="activityChoice" value "music"/> Music ($30.00)<br> <input type="radio" name="activityChoice" value "swimming"/> Swimming ($25.50)<br> <input type="radio" name="activityChoice" value "tennis"/> Tennis ($20.00)<br> <input type="radio" name="activityChoice" value "basketball"/> Basketball ($15.50)<br> <input type="radio" name="activityChoice" value "netball"/> Netball ($15.50)<br> <input type="radio" name="activityChoice" value "dance"/> Dance ($10.50)<br> <input type="radio" name="activityChoice" value "communityService"/> Community Service (No Charge)</td></tr> I have this thing that i am trying to make but i cant get it to work.. can anyone help? Code: [Select] function sql_read( $dbname,$dbusername,$dbpassword ) { $names = array(); $password = array(); $connect = @mysql_connect("mysql11.000webhost.com",$dbusername,$dbpassword) or die("Could Not Connect"); @mysql_select_db ($dbname) or die("Could not find DataBase"); $query = mysql_query("select * from users"); $numrows = mysql_num_rows($query); if ($numrows > 0){ while($row = mysql_fetch_assoc($query)){ $names[] = $row["uname"]; $password[] = $row["password"]; $id = $row["id"]; } $return = array($names,$password,$id); }else{ $return = array(); } return $return[]; } $names = array(); $names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0]; The error i get is Code: [Select] Parse error: syntax error, unexpected '[' in /home/a5480952/public_html/sql/index.php on line 28 Line 28 is "$names = sql_read("XXXXXX","XXXXXX","XXXXXXX")[0];" Please help... i REALLLLD need help with this.. ask questions if you want to know more about what i am trying to do... thanks! I'm having troubling with trying to create a function to spit out a single array with the following array. I can write it in a away that looks through the arrays manually. the results i am trying to generate is that each item in generated array. Array to convert array( "account" => array( "login", "register", "logout", "edit", ), "p" => array( "report", ), "array1.0" => array( "array2.0" => array( "array3.0", "array3.1 ), "array2.1", ), generating the array will look like this
Array ( [0] => account [1] => account/login [2] => account/register [3] => account/logout [4] => account/edit [5] => p [6] => p/report [7] => array1.0 [8] => array1.0/array2.0 [9] => array1.0/array2.0/array3.0 [10] => array1.0/array2.0/array3.1 [11] => array1.0/array2.1 ) The idea is that id generates a single array with combined labels and arrays inside, etc. I just can't figure out how to create a script that will create this array even If I add a new value or array.
I am trying to pull out the image HTML tag but its not working as expected. Here is what I am doing $removeimagetag='/<a href/'; $replacwith = "illegal"; $_POST['descr']=preg_replace($removeimagetag,$replacwith,$_POST['descr']); in the 'descr' there is a <a href="http://s635.photobucket.com...... When it post it does not strip out the <a href So the image is displayed. I tried a modified version to test to see if it work that looked like this. $removeimagetag='/goofy/'; $replacwith = "illegal"; $_POST['descr']=preg_replace($removeimagetag,$replacwith,$_POST['descr']); When the word goofy appears in the text then its replaced with the word illegal, Also I would like to make it so that it replaces the entire line from the <a href....... to the </a> with a phrase that says "this feature is not allowed" rather than just the part in the front...the <a href. Any help you can be will be greatly appreciated. Hi everyone, how do i add and ampersand symbol into preg_replace preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/" where do i place the symbol? & i have: $msg = ereg_replace("[^A-z0-9]"," ",$msg); $msg = ereg_replace(" "," ",$msg); $msg = ereg_replace(" "," ",$msg); how will i apply preg_replace please??? thank you Hi, I'm kind of new to PHP and very new to Regular Expressions and I was wondering if someone could help run through this code snippet from a callback function in a Joomla plugin called Affliates Feed. So far I have this is passed a pointer to variable item (I understand this is effectively the same as passing the variable but a lot less CPU intensive. Creates an array with keys and values Now the for loop I am stuck with, I understand the interation through the array. But what is preg_replace returning and why pass it back that way hasn't it already done its job? Can any one help? And please feel free to be as basic as possible :help: Thanks, Adam Code: [Select] function gardening(&$item) { #renaming categories, not the most efficient use for example strtolower first, and use only lowercase in the rename array $rename=array( ' Gardening?' => '', 'Climber Plants' => 'Climbing Plants', 'Seeds.*Bulbs' => 'Seeds Bulbs', 'Plant protection' => 'Horticultural goods', 'Garden structures' => 'Garden buildings',); foreach ( $rename as $k => $v ) { list($item['menu_1'],$item['menu_2'])=preg_replace("#$k#",$v,array($item['menu_1'],$item['menu_2'])); } $item['menu_1']=ucfirst(strtolower($item['menu_1'])); $item['menu_2']=ucfirst(strtolower($item['menu_2'])); $item['menu_3']=ucfirst(strtolower($item['menu_3'])); $item['menu_4']=ucfirst(strtolower($item['menu_4'])); } im trying to do a complex(i think) prg replace but i keep getting the error: Code: [Select] Failed evaluating code: $lang->showing-1,1 the code i am trying to replace is: Code: [Select] <asf: lang[showing-<asf: var[num_report_alerts]>,<asf: var[num_report_alerts]>]> and the preg_replace is: Code: [Select] $content = preg_replace('|\<asf: lang\[(.*?)-(.*?)\]\>|e', '$lang->replace_vars($lang->//1, array(\\2))', $content); its supposed to take everything inside <asf: lang[]> and echo \\1 which would be "showing" and then add \\2 into an array which would be "array(1,1)". So the output would be showing 1 of 1. Anyone know where im going wrong? After days of searching I found this thread http://www.phpfreaks.com/forums/index.php?topic=236954.0 that helped me do what I was trying to do. I've gotten the code to create and rename my html document but I can't figure out how to use the preg_replace part. This is my template with the 3 variables I want to replace with values from a form. Code: [Select] <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <?php include_once('content.php') ?> </body> <SCRIPT language="JavaScript" SRC="javascript.js"></SCRIPT> <script type="text/javascript"> function nametitle(){ parent.iframe1.document.getElementById("div1").innerHTML = "VARIABLE1 <br>VARIABLE2"; parent.iframe1.document.getElementById("quotes").innerHTML = "VARIABLE3"; } </script> </html> I've spent hours reading and trying to understand how to make it work but it's a little over my head. Could someone help me with this? Thanks, I currently have some custom tags, similar to BBCode, to be used for comments on my site. I'm trying to create a [nobr] tag (note: I know the no break tag will work in many major browsers, but it's deprecated, so I'm trying to be compliant). The idea is that if I encounter the [nobr] tag, I need to remove all line breaks. Here's the best I can do, but it's not working as I had hoped. Here's what I currently use to replace line breaks with a break tag. Code: [Select] $str=str_replace("\r\n","<br>",$str); Here's my attempt at introducing this new tag. Code: [Select] function BbToHtml($str) { $before=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\1",$str); $during=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\2",$str); $after=preg_replace("/(.+)\[nobr\](.+)\[\/nobr\](.+)/Usi","\\3",$str); $during=str_replace("\r\n","",$during); if($during != "") { // If the [nobr] tag was found, go with the new string. $str = $before.$during.$after; } else { // If the [nobr] tag was not found, go ahead like normal. $str=str_replace("\r\n","<br>",$str); } return $str; I can't get that working. Any ideas on how to fix that, or a completely alternate method of doing it? Thank you! Hello ppl, I have this website link http://www.somesite.com/anotherpage/yetotherpage.html what i want to make is using preg_replace that the final result will be www.somesite.com Hi there! I need to echo some text from a database table, this text should be linked to a url stored in the same database. I am trying to do this with preg_replace but I am terrible at it! I keep getting this error: Warning: Wrong parameter count for preg_replace() while($row = mysql_fetch_array( $result )) { $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; echo preg_replace ($reg_exUrl, $row['title'); Any suggestion? Thanks I'm trying to search a string for all occurences of a pattern, then append text after that pattern. The example is:
SUM("foo") as "bar"
and have it display as:
SUM("foo") over() as "bar"
The "SUM" could be any SQL aggregate and be case insensitive. So For bonus points, let's say the valid aggregates are array('SUM', 'MAX', 'MIN', 'AVG'). My plan right now is to figure it out for SUM, then loop it replacing the aggregate.
This is what I have so far... and it is not working.
$l= 'SUM("foo") as "bar"';
$l=preg_replace('/([^"]+")/','\0 over()',$l);
Thanks,
Ryan
This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=350441.0 |