Web-программирование на PHP 5.2 - ответы
Количество вопросов - 140
<?phpclass NumToText{ var $Mant = array(); var $Expon = array(); function NumToText() { } function SetMant($mant) { $this->Mant = $mant; } function SetExpon($expon) { $this->Expon = $expon; } function DescrIdx($ins) { if(intval($ins/10) == 1) // числа 10 - 19: 10 миллионов, 17 миллионов return 2; else { $tmp = $ins%10; if($tmp == 1) // 1: 21 миллион, 1 миллион return 0; else if($tmp >= 2 && $tmp <= 4) return 1; // 2-4: 62 миллиона else return 2; // 5-9 48 миллионов } } function DescrSot(&$in, $raz, $ar_descr, $fem = false) { $ret = ''; $conv = intval($in / $raz); $in %= $raz; $descr = $ar_descr[ $this->DescrIdx($conv%100) ]; if($conv >= 100) { $Sot = array('сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот'); $ret = $Sot[intval($conv/100) - 1] . ' '; $conv %= 100; } if($conv >= 10) { $i = intval($conv / 10); if($i == 1) { $DesEd = array('десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать' ); $ret .= $DesEd[ $conv - 10 ] . ' '; $ret .= $descr; return $ret; } $Des = array('двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто' ); $ret .= $Des[$i - 2] . ' '; } $i = $conv % 10; if($i > 0) { if( $fem && ($i==1 || $i==2) ) { $Ed = array('одна', 'две'); $ret .= $Ed[$i - 1] . ' '; } else { $Ed = array('один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять' ); $ret .= $Ed[$i - 1] . ' '; } } $ret .= $descr; return $ret; } function Convert($sum) { $ret = ''; $Kop = 0; $Rub = 0; $sum = trim($sum); $sum = str_replace(' ', '', $sum); $sign = false; if($sum[0] == '-') { $sum = substr($sum, 1); $sign = true; } $sum = str_replace(',', '.', $sum); $Rub = intval($sum); $Kop = $sum*100 - $Rub*100; if($Rub) { if($Rub >= 1000000000) $ret .= $this->DescrSot($Rub, 1000000000, array('миллиард', 'миллиарда', 'миллиардов')) . ' '; if($Rub >= 1000000) $ret .= $this->DescrSot($Rub, 1000000, array('миллион', 'миллиона', 'миллионов') ) . ' '; if($Rub >= 1000) $ret .= $this->DescrSot($Rub, 1000, array('тысяча', 'тысячи', 'тысяч'), true) . ' '; $ret .= $this->DescrSot($Rub, 1, $this->Mant) . ' '; $ret[0] = chr( ord($ret[0]) + ord('A') - ord('a') ); } if($Kop < 10) $ret .= '0'; $ret .= $Kop . ' ' . $this->Expon[ $this->DescrIdx($Kop) ]; if($sign) $ret = '-' . $ret; return $ret; }}class ManyToText extends NumToText{ function ManyToText() { $this->SetMant( array('рубль', 'рубля', 'рублей') ); $this->SetExpon( array('копейка', 'копейки', 'копеек') ); }}class MetrToText extends NumToText{ function MetrToText() { $this->SetMant( array('метр', 'метра', 'метров') ); $this->SetExpon( array('сантиметр', 'сантиметра', 'сантиметров') ); }}?><HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1251"> <title>Example from intuit.ru</title></HEAD><BODY><?phpif( isset($HTTP_POST_VARS['num']) ){ $mt = new ManyToText(); $nt = new MetrToText(); echo $mt->Convert($HTTP_POST_VARS['num']) . '<BR />'; echo $nt->Convert($HTTP_POST_VARS['num']) . '<BR />';}?><FORM ACTION ="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" METHOD="post">Input number:<BR /><INPUT TYPE="text" NAME="num"><BR /><INPUT TYPE="submit" VALUE=" GET "></FORM></BODY></HTML>
function add_some_extra(&$string) { $string .= 'and something extra.'; }$str = 'This is a string, '; add_some_extra($str);echo $str;
<html> <head> <title> Математические операторы </title> </head> <body> <h1> Математические операторы </h1> <?php echo "5 + 2 = ", 5 + 2, "<BR>"; echo "5-2=", 5-2, "<BR>" ; echo "5*2=", 5*2, "<BR>"; echo "5 / 2 = ", 5/2 , "<BR>"; echo "5 % 2 = ", 5 % 2, "<BR>"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="Вася::Петров::25::"; $array=explode("::",$string); echo "Имя: ".$array[0].", Фамилия: ".$array[1].", Возраст: ".$array[2]; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $file="base.txt"; $line="5"; $data="new line"; $array=file($file); $open=fopen($file,"w"); while(list($num,$string)=each($array)) { if(($num+1)==$line) fwrite($open,$data."\r\n"); fwrite($open,$string); } fclose($open); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php echo phpversion(); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "12345-1234"; $pattern = '/\d{5}-d{4}/'; echo preg_match($pattern, $subject); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="ВоЛнОоБрАзНыЙ ТеКсТ"; $string=strtolower($string); echo $string; ?> </body> </html>
mysql>CREATE TABLE drivers( name CHAR(30) NOT NULL, second_name CHAR(30) NOT NULL, family_name CHAR(30) NOT NULL, birth DATE NOT NULL, address CHAR(150) NOT NULL DEFAULT 'unknown', startdate DATE NOT NULL DEFAULT '2002-01-01', id SMALLINT AUTO_INCREMENT, PRIMARY KEY (id));
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $max=min(max(max(max(5,5,5,5,5,4,5),6), min(7,6)),7); echo "Numbers: ".$max; ?> </body> </html>
<html> <head> <title>Инкремент и декремент</title> </head> <body> <h1>Инкремент и декремент</h1> <?php $а = $b = $c = $d = 1; echo "\$а+ + = ", $а++, "<BR>"; echo "+ +\$b =", ++$b, "<BR>"; echo "\$c-- = ", $c--, "<BR>"; echo "--\$d=", --$d, "<BR>"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $var = "Строка состоит из 29 символов"; echo substr_replace($var, " ", 18, 2)."<br/>\n"; ?> </body> </html>
<html> <head> <title> Присваивание значений переменным </title> </head> <body> <h1>Присваивание значений переменным</h1> <?php echo "Количество яблок устанавливается в 1.<BR>"; $apples = 1; echo "Число яблок: ", $apples, "<BR>"; echo "Добавляется 3 яблока.<br>"; $apples = $apples + 3; echo "Теперь число яблок: ", $apples, "<BR>"; ?> </body> </html>
<html> <head> <title> Интерполяция переменных </title> </head> <body> <h1> Интерполяция переменных </h1> <?php $text = "news" ; echo "Where's the {$text}paper"; ?> </body> </html>
<?php $score = 4; if ($score == 5) echo "Отлично"; else { if ($score == 4) echo "Хорошо"; else { if ($score == 3) echo "Удовлетворительно"; else echo "Неудовлетворительно"; } }?>
if ($i == 0) {print "i equals 0";}if ($i == 1) {print "i equals 1";}if ($i == 2) {print "i equals 2";}
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $var = "Двадцать пять"; echo "Оригинал: $var <hr/>\n"; echo substr_replace($var, "25", 0)."<br/>\n"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "12212345678 - 1234"; $pattern = '/^\d{5}$/'; echo preg_match($pattern, $subject); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "Здесь всего четыре слова"; $pattern = "/(всего)\s\w+\s(слова)/"; $new_subj = preg_replace($pattern,'\1 три \2',$subject); echo $new_subj; ?> </body> </html>
mysql> SELECT model,color FROM cars;
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $open=fopen("my_file.txt","w+"); fwrite($open,"строка\r\n"); fclose($open); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="хорошая сегодня погода, верно?"; $string=convert_cyr_string($string,"w","k"); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="ура! Тетя Ася приехала"; $string=ucfirst(strtolower($string)); echo $string; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $files=array( "file1.txt", "file2.txt", "file3.txt" ); for($i=0;$i<count($files);$i++) { $array[]=file($files[$i]); } while(list(,$result)=each($array)) { for($i=0;$i<count($result);$i++) { $new_array[]=$result[$i]; } } print_r($new_array); ?> </body> </html>
my_first_line - первая строка файла my_second_line - вторая строка файла my_third_line - третья строка файла my_fourth_line - четвертая строка файла my_fifth_line - пятая строка файла my_sixth_line - шестая строка файла
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $file="text.txt"; $array=file($file); echo $array[rand(0,count($array)-1)]; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $arr = array(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); unset($arr[0], $arr[2], $arr[4], $arr[6], $arr[8]); for($i = 0; $i < 10; $i++) { if(isset($arr[$i])) echo "$"."arr[$i] = ".$arr[$i]." определен <br>"; else echo "$"."arr[$i] = ".$arr[$i]." не определен <br>"; } ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $arr = array( array(‘Вася’, ‘слесарь’, 2500 ), array(‘Миша’,’строитель’, 3000), array(‘Андрей’, ‘шофер’, 2700) ); for ($i = 0; $i < 3; $i++) { for ($j=0; $j <3; $j++) { echo ' | '.$arr[$i][$j]; } echo '.<br>'; } ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php var_dump(pow(2,8)); echo "<br>"; echo pow(-1,20)."<br>"; echo pow(0, 0)."<br>"; echo pow(-1, 5.5)."<br>";?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_shift($stack); print_r($stack);?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head><?php $input = array("red", "green", "blue", "yellow"); array_splice($input, 2); print_r($input); echo "<br>"; $input = array("red", "green", "blue", "yellow"); array_splice($input, 1, -1); print_r($input); echo "<br>"; $input = array("red", "green", "blue", "yellow"); array_splice($input, 1, count($input), "orange"); print_r($input); echo "<br>"; $input = array("red", "green", "blue", "yellow"); array_splice($input, -1, 1, array("black", "maroon")); print_r($input); echo "<br>"; $input = array("red", "green", "blue", "yellow"); array_splice($input, 3, 0, "purple"); print_r($input); echo "<br>";?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $dayofmonth = date('t'); $day_count = 1; $num = 0; for($i = 0; $i < 7; $i++) { $dayofweek = date('w', mktime(0, 0, 0, date('m'), $day_count, date('Y'))); $dayofweek = $dayofweek - 1; if($dayofweek == -1) $dayofweek = 6; if($dayofweek == $i) { $week[$num][$i] = $day_count; $day_count++; } else { $week[$num][$i] = ""; } } while(true) { $num++; for($i = 0; $i < 7; $i++) { $week[$num][$i] = $day_count; $day_count++; if($day_count > $dayofmonth) break; } if($day_count > $dayofmonth) break; } echo "<table border=1>"; for($i = 0; $i < count($week); $i++) { echo "<tr>"; for($j = 0; $j < 7; $j++) { if(!empty($week[$i][$j])) { if($j == 5 || $j == 6) echo "<td><font color=red>".$week[$i][$j]."</font></td>"; else echo "<td>".$week[$i][$j]."</td>"; } else echo "<td> </td>"; } echo "</tr>"; } echo "</table>"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $line="1"; $file=file("my_file.txt"); $open=fopen("my_file.txt","w"); for($i=0;$i<count($file);$i++) { if(($i+1)!=$line){fwrite($open,$file[$i]);} } fclose($open); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "a4bcder4f"; $pattern = '/\d/'; echo preg_match($pattern, $subject); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="Мой дядя самых честных правил."; $symbols=strlen($string); echo $symbols; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $numeric="20.2347823947"; $numeric=round($numeric,3); echo $numeric; ?> </body> </html>
<html> <head> <title> Использование оператора echo </title> </head> <body> <h1>Отображение текста</h1> <?php echo "Привет от PHP!"; ?> <h1>Отображение дополнительного текста</h1> <?php echo "Снова привет от РНР!"; ?> </body></html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $pattern = "/(\w+)\s(\w+)\s(\w+)/"; $subject = "Александр Иванович Привалов"; $matches = preg_replace($pattern,'\3, \1 \2',$subject); echo $matches; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "Мой телефон - 211-22-33"; $pattern = '/([2-8]{1}[0-9]{2})-([0-9]{2}-[0-9]{2})/'; echo preg_match($pattern, $subject, $matches); print_r($matches); ?> </body> </html>
<?php$temperature = 35;if (($temperature >= 25) && ($temperature <= 30)) { echo ("Температура комфортна"); } else { echo ("Температура некомфортна"); }?>
<?php $foo = 1 + "10.5"; $foo = 1 + "-1.3e3"; $foo = 1 + "bob-1.3e3"; $foo = 1 + "bobЗ"; $foo = 1 + "10 Small Pigs"; $foo = 4 + "10.2 Little Piggies"; $foo = "10.0 pigs " + 1; $foo = "10.0 pigs " + 1.0; ?>
<?php$a = $b = $c = 1;echo $a, ", ", $b, ", ", $c;?>
<?php $text = "Жизнь "; $total = 150; echo $text .= "прекрасна. "; echo "Результат = ", $total /= 3;?>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $numeric="8.3"; $numeric=round($numeric); echo $numeric; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="55?"+"/55"; if(is_numeric($string)) {echo "число";} else {echo "не число";} ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $src = fopen('f1.txt', 'r'); $dst = fopen('f2.txt', 'w'); while ( !feof($src) ) { $line = fgets($src, 16); $line++; fputs($dst, $line); } fclose($dst); fclose($src); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <?php$string = "This is\tan example\nstring";/* в качестве разделителей используем пробел, табуляцию и перевод строки */$tok = strtok($string, " \n\t");while ($tok) { echo "Word=$tok<br />"; $tok = strtok(" \n\t");}?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $str = "123 234 345 456 567"; $result = preg_match('/\d(\d)\d/', $str, $found); echo "Matches: $result <br>"; print_r($found); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "12212345 - 1234"; $pattern = '/^\d{5}/'; echo preg_match($pattern, $subject); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head><?php $a = array(2, 4, 6, 8); echo "sum(a) = " . array_sum($a) . "<br>"; $b = array("a" => 1.2, "b" => 2.3, "c" => 3.4); echo "sum(b) = " . array_sum($b) . "<br>";?> </body> </html>
<html> <head> <title> Переменные, содержащие имена переменных </title> </head> <body> <H1>Переменные, содержащие имена переменных</H1> <?php $apples = 4; $oranges = 3; $fruitname = "oranges"; echo "Число апельсинов: ${$fruitname} <BR>"; $fruitname = "apples"; echo "Число яблок: ${$fruitname} <BR>"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $file=file("text.txt"); $strings="5"; for($i=0;$i<$strings;$i++) { $string.=$file[$i]; } echo $string; ?> </body> </html>
<html> <head> <title> Строковые операторы </title> </head> <body> <?php $a = "Жизнь"; echo "\$a = " , $a, "<BR>"; echo "\$b = \$a . \" прекрасна \"<BR>"; $b = $a . " прекрасна "; echo "Теперь \$b = ", $b, "<BR> "; echo "\$b .= \" и удивительна.\" <BR>" ; $b .= "и удивительна."; echo "Теперь \$b = ", $b, "<BR>"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?> </body> </html>
mysql> CREATE TABLE cars( model CHAR(50) NOT NULL, madein YEAR(4) NOT NULL, reg_number CHAR(12) NOT NULL, color CHAR(15) NOT NULL, id SMALLINT AUTO_INCREMENT, PRIMARY KEY(id));
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $line="1"; # строка, которую нужно изменить $replace="new string"; # на что нужно изменить $file=file("my_file.txt"); $open=fopen("my_file.txt","w"); for($i=0;$i<count($file);$i++) { if(($i+1)!=$line){fwrite($open,$file[$i]);} else{fwrite($open,$replace."\r\n");} } fclose($open); ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <?php $trans = array ("a" => 1, "b" => 1, "c" => 2); $trans = array_flip ($trans); print_r($trans);?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $string="Zmlyc3RfcmVjb3Jk"; # раскодируемое $decoded=base64_decode($string); echo $decoded; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <?php $string = "Hello world!"; echo $string."<br>"; $new_string = strrev($string); echo $new_string."<br>"; echo strrev($new_string)."<br>"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head><?php $food = array('fruits' => array('orange', 'banana', 'apple'), 'veggie' => array('carrot', 'collard', 'pea')); echo count($food, COUNT_RECURSIVE)."<br>"; echo count($food)."<br>";?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $var = "Строка букв"; echo "Оригинал: $var <hr/>\n"; echo substr_replace($var, "цифр", 7)."<br/>\n"; ?> </body> </html>
<html> <head> <title>Example from intuit.ru</title> </head> <body> <?php $subject = "ПРИМЕР СТРОКИ, СОСТОЯЩЕЙ ИЗ ЗАГЛАВНЫХ БУКВ"; $pattern = '/[а-я]/i'; echo preg_match($pattern, $subject); ?> </body> </html>
mysql>CREATE TABLE timetable( use_on DATE DEFAULT NULL, car_number SMALLINT, driver_number SMALLINT, id SMALLINT AUTO_INCREMENT, PRIMARY KEY(id), INDEX (car_number), INDEX (driver_number) , FOREIGN KEY (car_number) REFERENCES cars (id), FOREIGN KEY (driver_number) REFERENCES drivers (id) );