PHP - How To Pass Text Box Value To A Php Function?
Kindly let me know how can i assign values to a php function from any textbox when user clicks on the submit button???
Code: [Select] <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> <input type="submit" /> </form> Similar TutorialsCant seem to figure this one out for a chained script. In the code below I need to take the value of $drop_var from function drop_1() and send it to function drop_2() So I can add it to the Where clause to limit the results of the third box a little more. But I cannot get the value to pass to the function. Any help appreciated. func.php <?php //************************************** // Page load dropdown results // //************************************** function getTierOne() { $result = mysql_query("SELECT DISTINCT branch FROM rank") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['branch'].'">'.$tier['branch'].'</option>'; } } //************************************** // First selection results // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { include_once('db.php'); $result = mysql_query("SELECT DISTINCT type FROM rank WHERE branch='$drop_var'") or die(mysql_error()); echo '<select name="drop_2" id="drop_2"> <option value=" " disabled="disabled" selected="selected">Choose one</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['type'].'">'.$drop_2['type'].'</option>'; } echo '</select>'; echo "<script type=\"text/javascript\"> $('#wait_2').hide(); $('#drop_2').change(function(){ $('#wait_2').show(); $('#result_2').hide(); $.get(\"func.php\", { func: \"drop_2\", drop_var2: $('#drop_2').val() }, function(response){ $('#result_2').fadeOut(); setTimeout(\"finishAjax_tier_three('result_2', '\"+escape(response)+\"')\", 400); }); return false; }); </script>"; } //************************************** // Second selection results // //************************************** if($_GET['func'] == "drop_2" && isset($_GET['func'])) { drop_2($_GET['drop_var2']); } function drop_2($drop_var2) { echo "<br>($drop_var)<br>"; include_once('db.php'); $result = mysql_query("SELECT * FROM rank WHERE type='$drop_var2'") or die(mysql_error()); echo '<select name="drop_3" id="drop_3"> <option value=" " disabled="disabled" selected="selected">Choose one</option>'; while($drop_3 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_3['grade'].'">'.$drop_3['grade'].'</option>'; } echo '</select>'; echo '<input type="submit" name="submit" value="Submit" />'; } ?> index.php <?php include('db.php'); include('func.php'); ?><!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>Chained Select Boxes using PHP, MySQL and jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("func.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } function finishAjax_tier_three(id, response) { $('#wait_2').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> </head> <body> <p> <form action="" method="post"> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Category</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> <span id="wait_2" style="display: none;"> <img alt="Please Wait" src="ajax-loader.gif"/> </span> <span id="result_2" style="display: none;"></span> </form> </p> <p> <?php if(isset($_POST['submit'])){ $drop = $_POST['drop_1']; $drop_2 = $_POST['drop_2']; $drop_3 = $_POST['drop_3']; echo "You selected a "; echo $drop_3." ".$drop." ".$drop_2; } ?> </body> </html> hello how do i pass a value from 1 function to another i want to use this part Code: [Select] //send the list order to the navigation or list page $PHL = PhLists::by_listNo($PHGlno); foreach ($PHL as $PHLs){ $PHLlno = $PHLs->phList_No; $PHLorb = $PHLs->orderBy; $PHLord = $PHLs->orderDir; } from this very long function. Code: [Select] function include_placeHolders($position, $phNo, $pageID){ $langBS = basicSettings::find_by_id(1); $langID = $langBS->language_id; //FIND PLACEHOLDER BY ID $PH = Placeholders::find_by_pageID($pageID); foreach ($PH as $PHs){ $PHpos = $PHs->position; $PHnum = $PHs->phNumber; $PHgNo = $PHs->phGroup_No; $PHgFx = $PHs->PHGfx_id; $PHgThm = $PHs->PHGtheme_id; if($phNo == $PHnum && $position == $PHpos){ //FIND ELEMENT THEMES echo '<style type="text/css" media="screen">'; include(PAGES.DS."phGroups".DS."theme{$PHgThm}".DS."css".DS."styles.css"); echo '</style>'; echo'<div id="PHgroup">'; //FIND GROUPS BY phGroupNo $PHGodr = PhGroups::find_order($PHgNo); foreach ($PHGodr as $PHGodrs){ $PHGob = $PHGodrs->orderBy; $PHGod = $PHGodrs->orderDir; } //FIND PHGROUPS BY BY GROUPno & ORDER $PHG = PhGroups::find_by_order($PHgNo, $PHGob, $PHGod); foreach ($PHG as $PHGs){ $PHGid = $PHGs->id; $PHGname = $PHGs->name; $PHGgno = $PHGs->phGroup_No; $PHGlno = $PHGs->list_No; $PHGce = $PHGs->contElements_id; $PHGpl = $PHGs->pageLink_id; $extLink = $PHGs->extLink_id; $PHfx = $PHGs->PHfx_id; $PHthm = $PHGs->PHtheme_id; //send the list order to the navigation or list page $PHL = PhLists::by_listNo($PHGlno); foreach ($PHL as $PHLs){ $PHLlno = $PHLs->phList_No; $PHLorb = $PHLs->orderBy; $PHLord = $PHLs->orderDir; } //FIND EXTERNAL LINK $PHGeL = ExtLinks::find_link($extLink); foreach($PHGeL as $PHGeLs){ $PHGurl = $PHGeLs->url; $PHGtarget = $PHGeLs->target; } //FIND ELEMENTS $CE = ContElements::find_by_phg($PHGce); foreach ($CE as $CEs){ $CEeName = $CEs->name; $CEetype = $CEs->elementTypes_id; $CEefx = $CEs->elFx_id; $CEethm = $CEs->elTheme_id; //FIND ELEMENT TYPE NAME $CEt = ElementsTypes::find_Etype($CEetype); foreach ($CEt as $CEts){ $CEtName = $CEts->name; //FIND PLACEHOLDER THEMES echo '<style type="text/css" media="screen">'; include(PAGES.DS."placeHolders".DS."theme{$PHthm}".DS."css".DS."styles.css"); echo '</style>'; //FIND ELEMENT THEMES echo '<style type="text/css" media="screen">'; include(ELEMENTS.DS."{$CEtName}".DS."themes".DS."theme{$CEethm}".DS."css".DS."styles.css"); echo '</style>'; //FIND INTERNAL OR EXTERNAL LINK $pageLNK = (empty($PHGpl)) ? '' : '<a href="index.php?pageID='.$PHGpl.'">'; $extLNK = (empty($extLink)) ? '' : '<a href="'.$PHGurl.'" target="'.$PHGtarget.'">'; $ENDpageLNK = (empty($PHGpl)) ? '' : '</a>'; $ENDextLNK = (empty($extLink)) ? '' : '</a>'; echo $pageLNK; echo $extLNK; echo'<div id="ph"> <div id="PHelement">'; include(ELEMENTS.DS."{$CEtName}".DS."{$CEeName}.php"); echo'</div></div>'; echo $ENDpageLNK; echo $ENDextLNK; } } } echo'</div>'; } } } i want the next long function to use these values Quote $PHLlno = $PHLs->phList_No; $PHLorb = $PHLs->orderBy; $PHLord = $PHLs->orderDir; this is where i want to use them in the next function Quote $nH = PhLists::navOrder($PHLlno, $PHLorb, $PHLord); Code: [Select] function nav(&$navLink){ $nH = PhLists::navOrder($PHLlno, $PHLorb, $PHLord); foreach ($nH as $nHs){ $nav_typ = $nHs->type; $nav_lvl = $nHs->levels; $nav_pLnk = $nHs->pageLink_id; $nav_eLnk = $nHs->extLink_id; $nav_tType = $nHs->titleType; $nav_ctBid = $nHs->custTxtBridge_id; //INTERNAL LINKS if($nav_typ == "Internal"){ //USE SET TITLE if($nav_tType == "SetTitle"){ $navPage = Pages::findNav($nav_pLnk); foreach ($navPage as $navPages){ $NPbid = $navPages->PCbridge_id; } $STBhead = PCbridge::find_setTitle($NPbid, $langID); foreach ($STBhead as $STBheads){ $text = $STBheads->pageContent_id; } $navText = PageContent::find_text($text); foreach ($navText as $navTexts){ $navLink = $navTexts->title; } //USE CUSTOM TITLE }else if($nav_tType == "Custom"){ $CTBhead = PCbridge::find_customTitle($nav_ctBid, $langID); foreach ($CTBhead as $CTBheads){ $text = $CTBheads->pageContent_id; } $navText = PageContent::find_text($text); foreach ($navText as $navTexts){ $navLink = $navTexts->title; } } } //EXTERNAL LINKS if($nav_typ == "External"){ //USE SET TITLE if($nav_tType == "SetTitle"){ $navExt = ExtLinks::findNav($nav_eLnk); foreach ($navExt as $navExts){ $navLink = $navExts->name; $PHGurl = $navExts->url; $PHGtarget = $navExts->target; } //USE CUSTOM TITLE }else if($nav_tType == "Custom"){ $navExt = ExtLinks::findNav($nav_eLnk); foreach ($navExt as $navExts){ $PHGurl = $navExts->url; $PHGtarget = $navExts->target; } $CTBhead = PCbridge::find_customTitle($nav_ctBid, $langID); foreach ($CTBhead as $CTBheads){ $text = $CTBheads->pageContent_id; } $navText = PageContent::find_text($text); foreach ($navText as $navTexts){ $navLink = $navTexts->title; } } } //NO LINK if($nav_typ == "Non"){ //USE CUSTOM TITLE if($nav_tType == "Custom"){ $CTBhead = PCbridge::find_customTitle($nav_ctBid, $langID); foreach ($CTBhead as $CTBheads){ $text = $CTBheads->pageContent_id; } $navText = PageContent::find_text($text); foreach ($navText as $navTexts){ $navLink = $navTexts->title; } } } } } thanks Hi, Im trying to pass a variable ($in_this_instance) into, and then back out of a function. The variable goes into the function no problem, and is echo'ed out fine. However the echo after the close of the function, does not give anything out. Code: [Select] $in_this_instance = 'boo'; function in_this_instance($data) { global $in_this_instance; echo $in_this_instance; $in_this_instance = 'hoo'; $rep_val = '[front banner]'; $test = strpos($data, $rep_val); if ($test === false) { return $data; } else { return $data;; } } add_filter('the_content', 'in_this_instance'); echo $in_this_instance; Could any one give me a pointer please? Many Thanks! Hi All, I have a function that i want to pass a variable into so that i can do some SQL on it. The information that i want to pass into it is a data-id on a button that is used to trigger the function. The button that will be clicked is this <div class='modaltrigger btn btn-primary' data-id='$itemId' data-toggle='modal'>Manage</div> This button is being created by another function. I would like to know either how i pass the variable from one function to another or how i pass it from the data-id to the function in php. Thanks in advance. Hi guys, I have a trouble with my php snippet, when I insert the var function in the url bar something is like: http://www.mysite.com/delete.php?favorites&id=0 or http://www.mysite.com/delete.php?whateveritis&id=0 It doesn't get pass the favorites function to delete the id. It is the same things that it goes for each different function. Here's the current code: <?php Code: [Select] session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbtablename'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $favorites = clean($_GET['favorites']); $id = clean($_GET['id']); if($favorites && $id == ''){ // both are empty $errmsg_arr[] = 'favorites id are missing.'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['id'])) { $insert[] = 'id = \'' . clean($_GET['id']) .'\''; } if(isset($_GET['favorites'])) { $insert[] = 'favorites = \'' . clean($_GET['favorites']) . '\''; } if($favorites && $id) { mysql_query("DELETE FROM favorites WHERE id='$id'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo "favorites channels is deleted"; } else { echo("favorites is already deleted"); } } } ?> If you do know how to get pass the favorites function, then please say so as i need your help. Any advice would be much appreicated. I need someone to explain how to loop through an array ($products) and grab the three values (name, price, & shipping) and have them sent to "all_products" function - see line 13 then 61 thru 64. I currently have the script partially working by using array_shift which I know is removing the 1st element (name or $product value). Note: this is the problem (I need $product included in the call to the "all_products" function along with $price & $shipping so that the final output looks as follow: --------------------------------- Checkout Below is a summary of the products you wish to purchase, along with totals: * Candle Holder: $12.95 * Coffee Table: $99.5 * Lamp: $42.99 Total (including tax and shipping): $182.12 ------------------------------------------------------ HERE'S THE SCRIPT FOR REVIEW & COMMENT: =============================== <B>Checkout</B><br> Below is a summary of the products you wish to purchase, along with totals: <?php /* Fix this code by creating a function to determine sub-totals for each product. Then add the sub-totals together to arrive at the grand total.The product name, & price should display for each item. ?><ul><? /* "all_products" function was created to query then calculate the sub-totals for each prodcut, then add each sub-total togehter to form grand total - outside the function */ function all_products($prod_array) { extract($prod_array); #tax rate is constant $tax = 0.08; $total_price = 0; $total_tax = 0; $total_shipping = 0; // Calculations per product with returned sum sent outside to $grand_total variable $total_price += $price; $total_tax += $tax * $price; $total_shipping += $shipping * $price; $sub_total = ($total_price + $total_tax + $total_shipping); # This calculates the sub-total (or Grand total) for each product echo "<li>".$product.": $".$price."<br />"; # THE PRODUCT NAME & PRICE SHOULD DISPLAY HERE (NAME IS NOT SHOWING WHICH IS PROBLEM) # I had echo statement to confirm calculation on product was correct # echo "Grand Total is $".$sub_total."<br />"; return $sub_total; # This breaks out of the function when Candle Holder IF statement is true; returning value } /* Keep the functions, and add a two-dimensional array that acts as a product database -- it should contain the name, price, and shipping price for every product -- and use list() and each() to traverse the database. */ // Products array with List / Each configuration to pass arguements into function $products = array('Candle Holder' => array('price' => '12.95','shipping' => '0.00'), 'Coffee Table'=>array('price' => '99.50','shipping' => '0.10'), 'lamp' =>array('price' => '99.50','shipping' => '0.10')); while (list($k, $v) = each($products)) { $product = $k; # This is individual product name extracted from array #echo "Here's the price & shipping cost for ".$product.":<br/>"; while (list($key, $value) = each($v)) { if (array_key_exists('price',$v)) { $price = $value; #echo "The product ".$key." is: $".$value."<br />"; } if (array_key_exists('shipping',$v)) { $shipping = $value; #echo "The ".$key." cost is: ".$value."<br />"; } } } # THE BELOW THREEE LINES TRAVERSE THE ARRAY BUT STRIPPING THE 1ST ELEMENT WHICH IS NOT WHAT I WANT; I NEED THE INCLUDED TO DISPLRAY BEFORE PRICES $sub_total1 = all_products(array_shift($products)); $sub_total2 = all_products(array_shift($products)); $sub_total3 = all_products(array_shift($products)); echo "RESULTS OUTSIDE FUNCTION: ".$sub_total1."<br />"; echo "RESULTS OUTSIDE FUNCTION: ".$sub_total2."<br />"; echo "RESULTS OUTSIDE FUNCTION: ".$sub_total3."<br />"; // Add total sum for each product to define grand total for all products including shipping & taxes $grand_total = $sub_total1 + $sub_total2 + $sub_total3; ?> </ul> <hr> <br> <?php # Below is the "GRAND TOTAL" for all three project - displayed outside the function which should be $182.12 USD ?> <B>Total (including tax and shipping): $<? echo number_format($grand_total, 2); ?></B> Hello everyone, Can someone show me a way how to pass $_post variable from a form to a function? So, input username and input password to a function login($username, $password). Hello All, I have used a function to collect a users information from the database. This is then returned as an array. Using this returned array, I wish to pass it into another function. Here is the code: The array is created in the collect() function and needs to be passed to the ipn_data function Code: [Select] /* This script is responsible for handling all subscription payments. It will collect all information, insert data into the relevant databases and then forward the user to PayPal with the relevant transaction ID. On return, the IPN listener will deal with all account changes whilst the user is held in a queue. */ /* ------------------------------------- */ /* DATABASE CONFIGURATION */ /* ------------------------------------- */ include_once "../config/config.php"; /* ------------------------------------- */ /* COLLECT SESSION INFORMATION */ /* ------------------------------------- */ session_start(); $id = "100000002"; // ID of logged in user $next_year = date("Y-m-d", strtotime("+365 day", time())); //Date next year /* ------------------------------------- */ /* SET VARIABLES */ /* ------------------------------------- */ $reason = $_GET["reason"]; /* ----------------------------------------- */ /* COLLECT USERS INFORMATION FROM DATABASE */ /* ----------------------------------------- */ function collect($id) { //Select the subscriber from the database $query = "SELECT * FROM subscribers WHERE id='$id'"; $query = mysql_query($query); //Collect the subscribers first name, last name and email address while($row=mysql_fetch_array($query)) { $fname = $row["fname"]; $lname = $row["lname"]; $email = $row["email"]; } //Collate subscribers information into an array return array('fname' => "$fname", 'lname' => "$lname", 'email' => "$email"); } /* ----------------------------------------- */ /* CREATE TIMESTAMP OF CURRENT TIME */ /* ----------------------------------------- */ function mktimestamp() { //Set date variables $day = date("d"); $month = date("m"); $year = date("Y"); //Make timestamp return mktime(0, 0, 0, $month, $day, $year); } /* ----------------------------------------- */ /* INSERT USERS DATA INTO ipn_data */ /* ----------------------------------------- */ //Create random identifier $ident = rand("1", "10000"); function ipn_data($info, $reason, $timestamp) { //WANT THE ARRAY TO BE PASSED INTO HERE!! //I TRIED PASSING THE $info VARIABLE INTO THE FUNCTION, WHICH IS WHAT I ASSIGNED TO THE COLLECT FUNCTION LATER IN THE SCRIPT } /* ----------------------------------------- */ /* Get ID of inserted ipn_data row */ /* ----------------------------------------- */ function get_id($ident, $timestamp) { //Setup Query to find ID $query = "SELECT * FROM subscribers WHERE timestamp='$timestamp' AND identifier='$ident'"; //Run Query $query = mysql_query($query) or mysql_error(); //Using query find ID while($row=mysql_fetch_array($query)) { $ltj_txn_id = $row["id"]; } return $ltj_txn_id or mysql_error(); } /* ------------------------------------- */ /* SWITCH REASON */ /* ------------------------------------- */ switch($reason) { case "subscribe": break; case "renew": //Collect array from user information array function $info = collect($id); //Get timestamp from our mktimestamp function $timestamp = mktimestamp(); //Insert users data into ipn_data table $run_ipn = ipn_data($reason, $timestamp, $ident); //Collect ID of record just inserted $get_id = get_id($ident, $timestamp); echo "$run_ipn"; break; case "upgrade": break; default: break; } Any ideas? I have the array defined and print_r (outside the function is show what I need...) However, I need to somewhay pass those three arguments - name, price, shipping (keys & values) into the "all_products" function and assign (inside the function) each element to a variable {name, price, shipping}. Code: [Select] function all_products($key,$value) { # This is where I'm lost - I know the values are passed to the function but how to I assign them to below variable? echo "$name"; echo "$price"; echo "$shipping"; // Products array defined to send values into "all_products" function & loop to display item name & individual pricing (using WHILE LOOP) $products = array('Product1' => array ( 'name' => 'item one', 'price' => '30.00', 'shipping' => '0.00'), 'Product2' => array ( 'item two', 'price' => '19.50', 'shipping' => '0.10'), 'Product3' => array ( 'item three', 'price' => '21.99', 'shipping' => '0.10') ); while (list($keys, $values) = each($products)) { while (list($k, $v) = each($values)) echo "Checking Looped Data Outside Function: <strong>$k: </strong> $v<br/>"; # echo "<pre>"; # print_r($value); # echo "</pre>"; # Trying to send array elements into "all_products" function & echo (name, price, shipping) keys and values inside that function all_products($k,$v); } If I have a parameter that has a default value, how do I pass nothing such that it uses the default value? Passing NULL does not work. Code: [Select] function test($to = "test@test.com", $from) { echo $to . "<BR>" . $from; } //This will NOT show "test@test.com" but instead an empty line test( NULL, "fake@fake.com" ); Is it possible to have a text field on my site, and the text that is entered into it, be given to another site that I auto redirect the user to? If it is possible, could somebody give me the exact code (I'm not a programmer) I would need to use? Thanks for any help on this. I work with a large codebase and I have this situation come up fairly often:
the legacy class has large objects such as:
$design->motor->dimensions->a; $design->motor->dimensions->bd; $design->specifications->weight; $design->data->height; //etcWhen I create a new class, that class sometimes operates on the specific data, so say: class MyClass { public function compute($weight, $height, $a) { //stuff } } //and I call this for example as such: (new MyClass())->compute($design->specifications->weight, $design->data->height, $design->motor->dimensions->a);CONS: Potential issue: if design specs change and I need to change things parameters in "compute" function, I need to "re-key" the variables I pass to the function, and adjust things accordinly in MyClass as wel. PROS: only the exact data is being passed, and this data can come from anywhere it is viable, so in effect the function is fairly well separated, I think. Alternative option for me is to pass the entire design object, i.e class MyClass { public function compute(&$design) //can also be done via DI through a setter or constructor. { print $design->specifications->weight; print ($design->data->height + $design->motor->dimensions->a); //stuff } } (new MyClass())->compute($design);PROS: In this case when things change internally in which variables are needed and how things are computed, I only need to change the code in compute function of the class itself. CONS: MyClass now needs to be aware of how $design object is constructed. When it comes to this parameter passing, and Dependency Injection like this in general, does Computer Science advocate a preference on this issue? Do I pass the entire object, or do I pass only the bits and pieces I need? I'm trying to get a simple table to display and am not sure how to make it happen. Table will have just 2 columns. A TIME and an EVENT. What I want to have happen is for the first row to show the TIME and next to that, the EVENT. If a TIME has more than one event going I want the next row to show an empty first cell and then the second event below the first. If I set up the loop the only way I know how (so far) it would also output the TIME value again and again as many times as there were events for that same time. For example what I don't want is: 9:15 Sunday School 9:15 Nursery Available What I do want is: 9:15 Sunday School Nursery Available Thanks. If I was pulling back data from MySQL that was like this "monkeys / dogs / cats", how would I grab just "monkeys" from that using PHP? In other words, I want to grab all text until a "/" is seen. I'm trying to use preg_replace but I can't get it working. function replaceContent($sContent) { $aReplaceTags = array( "'\[MENU-CARD\](.*?)\[/MENU-CARD\]'is" => '\\1', "'\[CONTACT-FORM\]'is" => "Contactform", ); return preg_replace(array_keys($aReplaceTags), array_values($aReplaceTags), $sContent); } This works great however when I change '\\1' into a function the output of '\\1' will always be 1. function replaceContent($sContent) { $aReplaceTags = array( "'\[MENU-CARD\](.*?)\[/MENU-CARD\]'is" => $this->loadMenuCard('\\1'), "'\[CONTACT-FORM\]'is" => "Contactform", ); return preg_replace(array_keys($aReplaceTags), array_values($aReplaceTags), $sContent); } Anyone knows what I am doing wrong? I'm trying to include a routine to catch an error but it doesn't seem to write to a text file within a function. just using the following simple code, even if I simply try to write a letter it doesn't work
if ($http_status == 200) { return $response; } else { $myfile = fopen("ErrorData.txt", "a+") or die("Unable to open file!"); $txt = date("H:i:sa d-m-Y")." / Error data- / ".json_encode($response)."\r\n"; fwrite($myfile, $txt); fclose($myfile); }
Edited September 13, 2019 by Dvae56 Added code Hi everybody, a few dasy ago i found a function which translates integers into text like this:
echo $number->written_number(101); // one hundred one
but i've got a problem, this function works fine on russian language, but that this function translate in 3 languages:
russian, english and ukrainian like this:
echo $number->written_number(101); // сто один - one hundred one - сто один
how can i add english and ukrainian languages?
When i tried to add this manually, it was okay but in one moment i received error, and all my script is broked, and now i don't know what to do, i've got a few hours to complete this test work, but unfortunately i've got no idea how to do this(
Pls help me somebody, i will infinitely grateful!!!
This is my code
<?php require_once('languages.php'); class numberTransfer extends languages { public function written_number($i, $female = false) { if (($i < 0) || ($i >= 1e9) || !is_int($i)) { return false; // Аргумент должен быть неотрицательным целым числом, не превышающим 1 миллион } if($i == 0) { return $this->N0. '</br>' .$this->N0eng; } else { return preg_replace( array('/s+/','/\s$/'), array(' ',''), $this->num1e9($i, $female) ); return $this->num1e9($i, $female); } } public function num_125($n) { /* форма склонения слова, существительное с числительным склоняется одним из трех способов: 1 миллион, 2 миллиона, 5 миллионов */ $n100 = $n % 100; $n10 = $n % 10; if(($n100 > 10) && ($n100 < 20)) { return 5; } elseif($n10 == 1) { return 1; } elseif(($n10 >= 2) && ($n10 <= 4)) { return 2; } else { return 5; } } public function num1e9($i, $female) { if($i < 1e6) { return $this->num1e6($i, $female); } else { return $this->num1000(intval($i/1e6), false) . ' ' . $this->Ne6[$this->num_125(intval($i/1e6))] . ' ' . $this->num1e6($i % 1e6, $female); } } public function num1e6($i, $female) { if($i < 1000) { return $this->num1000($i, $female); } else { return $this->num1000(intval($i / 1000), true) . ' ' . $this->Ne3[$this->num_125(intval($i/1000))] . ' ' . $this->num1000($i % 1000, $female); } } public function num1000($i, $female) { if($i < 100) { return $this->num100($i, $female); } else { return $this->Ne2[intval($i/100)] . (($i % 100)?(' '. $this->num100($i % 100, $female)):''). '</br>' .$this->Ne2eng[intval($i/100)]. (($i % 100)?(''. $this->num100($i % 100, $female)):'') ; } } public function num100($i, $female) { $gender = $female?1:0; if ($i < 20) { return $this->Ne0[$gender][$i]. '</br>' .$this->Ne0eng[$gender][$i]; } else { return $this->Ne1[intval($i / 10)] . (($i % 10)?(' ' . $this->Ne0[$gender][$i % 10]):''). '</br>' . $this->Ne1eng[intval($i / 10)] . (($i % 10)?(' ' . $this->Ne0eng[$gender][$i % 10]):''); } } } $number = new numberTransfer(); echo $number->written_number(101);as you can see i tried to glue array with russian language words with array with english laguage words. Probably i've got somethink like this: $number = new numberTransfer(); echo $number->written_number(101); сто один one one hundredодин one damn bullshit... Please people help me:) Say I have a chunk of code that looks like this (contains imagesx): Code: [Select] <span style="color: #0000BB">$width </span><span style="color: #007700">= </span><span style="color: #0000BB">imagesx</span><span style="color: #007700">(</span><span style="color: #0000BB">$img</span><span style="color: #007700">); <br /> within the code I would like to make all the php functions link to php.net I thought that the following code would work, but it does not, well because there is no spaces around the above word public function phpLinks($string){ $words = explode(" ", $string); $str = array(); foreach($words as $word){ if(function_exists($word)){ $str[] = preg_replace("/$word/i", '<a href="//php.net/'.strtolower($word).'">'.$word.'</a>', $word); }else{ $str[] = $word; } } return implode(" ", $str); } I now can not think of a good way to do this, so I am asking does anyone have any suggestions? Hello there, I am working on a script that will take a user submitted text and display the text in rainbow. I found a very nice function on the Internet and used it as my base. Here is an example of the code. Code: [Select] function rainbow($text) { /*** initialize the return string ***/ $ret = ''; /*** an array of colors ***/ $colors = array( 'ff00ff', 'ff00cc', 'ff0099', 'ff0066', 'ff0033', 'ff0000', 'ff3300', 'ff6600', 'ff9900', 'ffcc00', 'ffff00', 'ccff00', '99ff00', '66ff00', '33ff00', '00ff00', '00ff33', '00ff66', '00ff99', '00ffcc', '00ffff', '00ccff', '0099ff', '0066ff', '0033ff', '0000ff', '3300ff', '6600ff', '9900ff', 'cc00ff'); /*** a counter ***/ $i = 0; /*** get the length of the text ***/ $textlength = strlen($text); /*** loop over the text ***/ while($i<=$textlength) { /*** loop through the colors ***/ foreach($colors as $value) { if ($text[$i] != "") { $ret .= '<span style="color:#'.$value.';">'.$text[$i]."</span>"; } $i++; } } /*** return the highlighted string ***/ return $ret; } $post[message] = rainbow($post[message]); And it works very well Here is my problem. At times $post[message] will contain some basic html such as a bold tag, user smiley (img tag), a link tag, and so forth. How can I take my function above so that it doesn't edit and add the html font color coding for anything inside html tags where it just skips over them and leaves that part alone? I need this otherwise it will breakup every html tag I might have inside $post[message] and add a font color html tag to it, thus voiding all other html in it. |