PHP - Function To Translates Integers Into Text
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:) Similar Tutorialshow do I pull out two random integers at the same time without ever possibly choosing the same integer twice? Code: [Select] if( date('j') < 1 && > 14) { $EnrollDate = "1/".date('n')."/".date('y'); }else { $EnrollDate = "15/".date('n')."/".date('y'); } What could be wrong here, i cant work! I almost have this right, but not quite. I am trying to echo out the average score if a person scored above 70 and my averaging isn't correct. It should echo out 89, but instead the number is 63.25. The averaging is the only part not working. Everything else works as intended. I might not have my curly braces in the proper order or something. I think it's something stupid I am forgetting. Here is my code. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Array Test</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <?php function array_average_nonzero($scores) { return array_sum($scores) / count(array_filter($scores)); } $scores["Tim"] = 98; $scores["Tom"] = 80; $scores["Mike"] = 50; $scores["Jason"] = 25; foreach( $scores as $key => $value) if($value < 70){ echo "$key scored a $value which is less than 70. <br />\n"; } elseif ($value < 70); { echo "The average score of those who scored over 70 is: " .array_sum($scores) / count($scores) . "<br />"; } ?> </body> </html> I am wondering how can I insert integers in the database without manually input it in the form. I am looking to fill the product_id and customer_id table. I would do it but only by sequence and '' quotes at the VALUE part of an INSERT statement. Also condition the insert of product_id and customer_id according to the id in the SESSION variable. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { $userid = $_SESSION['id']; $username = $_SESSION['username']; $fname = $_POST['firstname']; $lname = $_POST['lastname']; $telephone = $_POST['telephone']; $city = $_POST['city']; $state = $_POST['state']; $itemname = $_POST['product_name']; $price = $_POST['price']; $details = $_POST['details']; $category = $_POST['category']; $subcategory = $_POST['subcategory']; $product_id = $_POST['product_id']; $customer_id = $_POST['customer_id']; $date_sold = $_POST['date_sold']; $sqlinsert = "INSERT INTO customers (id,firstname,lastname,telephone,city,state,product_name,price,details) VALUES('','$fname','$lname', '$telephone','$city','$state','$itemname','$price','$details')"; $sqlinsert2 = "INSERT INTO products (id,product_name,price,details,category,subcategory) VALUES('','$itemname','$price','$details','$category','$subcategory')"; $sqlinsert3 = "INSERT INTO sales (id,product_id, customer_id, date_sold) VALUES('','$product_id','$customer_id','$date_sold')"; $enterquery = mysql_query($sqlinsert) or die(mysql_error()); $enterquery2 = mysql_query($sqlinsert2) or die(mysql_error()); $enterquery3 = mysql_query($sqlinsert3) or die(mysql_error()); } ?> The above insert its respective fields in each table but how is it possible to INSERT it according to the SESSION['id]; so that it INSERT according to the costumer id plus that it generates and INSERT automatically in the product_id and customer_id related to the product_id and customer_id fields in products and customer table? without manually doing it. any references will be appriciated because the above code seems like the product_id and customer_id won't INSERT in relations to the customer and product table. One more thing the product_id and customer_id won't be pass from the form to this file but rather a value will be INSERT it in their field according to the id in customer and products table. Is it possible to perform type declaration which allows either an integer or a string digit (i.e. ctype-digit) instead of the following? function someFunction(int $id){} Looking at functions.arguments.type-declaration, I expect not. If not, would you recommend type casting before calling the function or removing type declaration from the function and performing the check manually within the function and throwing an applicable exception? Thanks Hi,
Is there any way to use the inbuilt filter functions in PHP to filter for integer values greater than 256? All examples that I saw had a max_range of 256. Kindly suggest. Thanks.
i hit a wtf moments print $_POST['idName']; // prints 0, correct, the value of the selected select element item is indeed 0 print '<br>'; $value = intval($_POST['idName']); // otherwise its a string if($value == 'empty') { print '<br>wtf does this get printed?'; } the $values value is the number zero, not the string 'empty', so why does it eval as one? Hi, I'm trying to retrieve the integer value between the <span> tag from a HTML source code.
HTML source code:
<span> (3861822) </span>This is the php code: <!DOCTYPE html> <html> <body> <?php //use curl to get html content function getHTML($url,$timeout) { $ch = curl_init($url); // initialize curl with given url curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error return @curl_exec($ch); } $html=getHTML("http://www.alibaba.com/Products",10); preg_match("/<span>(.*)<\/span>/i", $html, $match); $title = $match[1]; echo $title; ?> </body> </html>Whenever I try to run it, this error will come out: Notice: Undefined offset: 1 in C:\xampp\htdocs\myPHP\index.php on line 19. How to correct it so that it will display all the integer value within the tag name but without the bracket? Thanks Edited by Raex, 20 August 2014 - 01:38 AM. Well the topic may not sound very explicit. So I'll do my best to explain it here. I have a pull down menu as part of a form, which contains the months of the year. I'm trying to store the value of this form entry using the $_POST['month'] variable into a database but first, I need to convert the month values into their corresponding integer values( that is 1 for January, 2 for February etc), in order to easily do date calculations later down the road. Any ideas about how to do this? It may be helpful to include the code for the pull down menu. Code: [Select] <p><tab> Date of Birth: <?php //Make the month pull down menu. //Array to store months. $months = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); print '<select name= "month">'; foreach ($months as $key => $value) { print "\n<option value=\"$key\">$value</option>"; } print '</select>'; ?> </tab> <tab> <?php //Make the day pull down menu print '<select name= "day">'; for ($day = 1; $day <= 31; $day++) { print "\n<option value=\"$day\">$day</option>"; } print '</select>'; ?> </tab> <tab><?php //Make the year pull down menu print '<select name= "year">'; $start_year = date('Y'); for ($y = ($start_year - 18); $y >= 1900; $y--) { print "\n<option value=\"$y\">$y</option>"; } print '</select>'; ?> </tab> </p> 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. 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> 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? 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 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? is there a function that can send text messages using php? thru an sms modem? This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=306874.0 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. Hi all, I have a textarea field name brief in my php form. The problem is that users are entering phone numbers and email addresses in this field even though there is dedicated email and phone fields. I want a function to either delete the numbers and emails address automatically on this field or alert the user that numbers are not allowed in this field. I have include my form. Many thanks for your help Hello, I'm having a bit of a problem here, all help to this issues would be much appreciated I am trying to use text boxes to insert numbers into the database based on what is inputed. If I have a string, like this for example: $variable = 09385493; And I want to insert it into the database like this: mysql_query("INSERT INTO integers(number) VALUES ('$variable')"); When checking the integers table in my database, looking at the number field, the $variable that was inserted is outputted as 9385493 Notice the number zero was taken out of the front of the number. If the number is double 0's (009385493), both of those zero's would disappear, too. Thanks Everything about the email is sending except the message text does anyone know what the issue could be? here is the block of code that sends the email Thanks in advance Code: [Select] $image = "http://www.visualrealityink.com/dev/clients/arzan/snell_form/images/email.png"; echo "got to process form"; $target_path = "upload/"; $path = $target_path = $target_path . basename( $_FILES['file']['name']); $boundary = '-----=' . md5( uniqid ( rand() ) ); $message .= "Content-Type: application/msword; name=\"my attachment\"\n"; $message .= "Content-Transfer-Encoding: base64\n"; $message .= "Content-Disposition: attachment; filename=\"$path\"\n\n"; echo $path; $fp = fopen($path, 'r'); do //we loop until there is no data left { $data = fread($fp, 8192); if (strlen($data) == 0) break; $content .= $data; } while (true); $content_encode = chunk_split(base64_encode($content)); $message .= $content_encode . "\n"; $message .= "--" . $boundary . "\n"; $message .= $image . "<br />" . $_POST['name'] . "submitted a resume on our website. Please review the applications and contact the candidate if their resume is a fit for any open opportunities with the company. <br><br> Thank you. <br><br> SEI Team"; $headers = "From: \"Me\"<me@example.com>\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\""; mail('george@visualrealityink.com', 'Email with attachment from PHP', $headers, $message); |