티스토리 뷰

PHP COOK BOOK에서 알아두면 좋을듯한 내용 정리하기


1. String 


\n 새행 ( ASCII 10 )

\r 캐리지 리턴 ( ASCII 13 )

\t  Tab ( ASCII 9)

\\ BackSlash

\$ 달러기호

\" Double Quote

\0 through \777 10진수

\x0 through \xFF 16진수



print "\$\061\060.\x32\x35"; => $10.25


echo <<< 'EOD'

test111

    냐햐햐

EOD;

'dummy';


// 단어첫번째 대문자

print ucwords('1 monkey face'); ==> 1 Monkey Face 


//문자열 안에 변수 덧붙이기


print " I Have {$children} children"

print " You owe {$amounts['payment']} iii ";

print "My circle's diameter is {$circle->getDiameter()} inches. ";



echo strftime('%c', time() + 86400);


print ltrim("10 print a$", '0...9');

print rtrim("select * from turtles;", ";"); //; 제거됨


$words = preg_split('/\d\. /', 'my day: 1. get up 2. get dress 3. eat toast');

(

    [0] => my day: 

    [1] => get up 

    [2] => get dress 

    [3] => eat toast

)

$words = preg_split('/ x /i','31 inches x 22 inches x 9 inches');


Array

(

    [0] => 31 inches

    [1] => 22 inches

    [2] => 9 inches

)

$dwarves = 'dopey, sleepy, happy, grumpy, sneezy, bashful, doc';

$dwarves_arr = explode(',', $dwarves, 5);

Array

(

    [0] => dopey

    [1] =>  sleepy

    [2] =>  happy

    [3] =>  grumpy

    [4] =>  sneezy, bashful, doc

)

$math = "3 + 2 / 7 -9 ";

$stack = preg_split('/ *([+\-\/*]) */', $math, -1, PREG_SPLIT_DELIM_CAPTURE);

Array

(

    [0] => 3

    [1] => +

    [2] => 2

    [3] => /

    [4] => 7

    [5] => -

    [6] => 9 

)


랜덤 추출하기 


function pick_color() {

    $colors = array('red', 'orange', 'yellow', 'blue', 'green', 'indigo', 'violet');

    $i = mt_rand(0, count($colors) -1);

    return $colors[$i];

};


echo pick_color();




날짜 배열로 얻어오기

$a = getdate();


(

    [seconds] => 23

    [minutes] => 28

    [hours] => 21

    [mday] => 6

    [wday] => 4

    [mon] => 10

    [year] => 2016

    [yday] => 279

    [weekday] => Thursday

    [month] => October

    [0] => 1475756903

)



$a = localtime();Array ( [0] => 26 [1] => 29 [2] => 21 [3] => 6 [4] => 9 [5] => 116 [6] => 4 [7] => 279 [8] => 0 ) 0 => 초 1. 분 2. 시간 3. 날짜 4. 월 5. 년 6. 요일 7. 1년중 몇일 8. is daylight saving time in effect? 배열 추가$arr = array('apple', 'banana', 'coconut'); $arr = array_pad($arr, 5, '추가');<font face="맑은 고딕, sans-serif"><span style="white-space: normal;"> </span></font>
Array
(
    [0] => apple
    [1] => banana
    [2] => coconut
    [3] => 추가
    [4] => 추가
)


배열추출하기

$arr = array('apple', 'banana', 'coconut', 'dates');

$aList = array_splice($arr, 3);

Array
(
    [0] => dates
)
배열 머지하기  ( 왼쪽을 키값을 => 오른쪽 값으로 대체하기 )
$lc = array('a', 'b' => 'b');
$uc = array('A', 'b' => 'B');
$ac = array_merge($lc, $uc);
Array
(
    [0] => a
    [b] => B
    [1] => A
)



print_r($uc + $lc );

print_r($lc + $uc );

Array ( [0] => A [b] => B ) Array ( [0] => a [b] => b ) ;



배열비고 하기 왼쪽기준으로 추출

$old = array('To', 'be', 'or', 'not', 'to', 'be');

$new = array('To', 'be', 'or', 'whatever');

$difference = array_diff($old, $new);

Array
(
    [3] => not
    [4] => to
)

$old = array('To', 'Be', 'or', 'not', 'to', 'be');
$new = array('To', 'be', 'or', 'whatever');
$difference = array_diff($new, $old);
Array
(
    [3] => whatever
)

파일 줄단위로 읽으면서 매칭하는 텍스트 검색하여 결과 얻어오기
function print_matching_lines($file, $regex) {
    if ( !$fh = fopen($file, 'r') ) {
        return;
    }
    while ( false !== ($line = fgets($fh)) ) {
       if ( preg_match($regex, $line)) { print $line; }
    }
    fclose($fh);
}

print_matching_lines('log.txt' , '/^rasmus: /');

숫자형식 
// convert from base 2 to base 10
// $a = 27
$a = bindec(11011);
// convert from base 8 to base 10
// $b = 27
$b = octdec(33);
// convert from base 16 to base 10
// $c = 27
$c = hexdec('1b');

// convert from base 10 to base 2
// $d = '11011'
$d = decbin(27);
// $e = '33'
$e = decoct(27);
// $f = '1b'
$f = dechex(27);
자리수 올리기
$number = ceil(2.4);
printf("2.4 rounds up to the float %.02d", $number);

1~ 10 for 문 ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 )

<?php
for ($i = 0x1; $i < 0x10; $i++) {
print "$i\n";
}
7.3890560989307
// $exp (e squared) is about 7.389
$exp = exp(2);


2.4 rounds down to the float 2

$number = floor(2.4);
printf("2.4 rounds down to the float %.02d", $number);


배열랜덤 추출하기


function pick_color() {
$colors = array('red','orange','yellow','blue','green','indigo','violet');
$i = mt_rand(0, count($colors) - 1);
return $colors[$i];
}

mt_srand(34534);
$first = pick_color();
$second = pick_color();

// Because a specific value was passed to mt_srand(), we can be
// sure the same colors will get picked each time: red and yellow
print "$first is red and $second is yellow.";


날짜 diff

// 7:32:56 pm on May 10, 1965
$first = new DateTime("1965-05-10 7:32:56pm", new DateTimeZone('Asia/Seoul'));
// 4:29:11 am on November 20, 1962
$second = new DateTime("1962-11-20 4:29:11am", new DateTimeZone('Asia/Seoul'));
$diff = $second->diff($first);
date_default_timezone_set('Asia/Seoul');
// $stamp_future is 1733257500
$stamp_future = mktime(15, 25, 0, 12, 3, 2024);
// $formatted is '2024-12-03T15:25:00-05:00'
$formatted = date('c', $stamp_future);


시간을 날짜로 변경하기

$a = strtotime('march 10'); // defaults to the current year
$b = strtotime('last thursday');
$c = strtotime('now + 3 months');

배열추출하기 

Array ( [foo] =&gt; b )

$array = [3 => 'a', 'foo' => 'b', 5 => 'c', 'bar' => 'd'];
$offset = $length = 1;

$arr = array_splice($array, $offset, $length); // $array 1,1


$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals); //Array ( [0] => ant [1] => bee [2] => elk [3] => fox )


//배열 오른쪽에 dates 추가하기

$array = array('apple', 'banana', 'coconut');
$array = array_pad($array, 4, 'dates');
print_r($array);


//배열 앞에 깞 추가하기

$array = array('apple', 'banana', 'coconut');
$array = array_pad($array, 4, 'dates');
$array = array_pad($array, -6, 'zucchini'); //Array ( [0] => zucchini [1] => zucchini [2] => apple [3] => banana [4] => coconut [5] => dates )
print_r($array);


배열 while 문 사용하여 처리하기 

$states = array(1 => 'Delaware', 'Pennsylvania', 'New Jersey');
asort($states);

while (list($rank, $state) = each($states)) {
print "$state was the #$rank state to join the United States\n";
}


배열 탐색하기 

$names = array('firstname' => "Baba",
'lastname' => "O'Riley");

array_walk($names, function (&$value, $key) {
$value = htmlentities($value, ENT_QUOTES);
});

foreach ($names as $name) {
print "$name\n";
}


재귀적으로 하위 배열도 재 탐색할수 있도록 처리하기

$names = array('firstnames' => array("Baba", "Bill"),
'lastnames' => array("O'Riley", "O'Reilly"));

array_walk_recursive($names, function (&$value, $key) {
$value = htmlentities($value, ENT_QUOTES);
});

foreach ($names as $nametypes) {
foreach ($nametypes as $name) {
print "$name\n";
}
}


배열비교하기

$old = array('To', 'be', 'or', 'not', 'to', 'be');
$new = array('To', 'be', 'or', 'whatever');
$difference = array_diff($old, $new);
print_r($difference);


날짜 정렬하기

// expects dates in the form of "MM/DD/YYYY"
function date_sort($a, $b) {
list($a_month, $a_day, $a_year) = explode('/', $a);
list($b_month, $b_day, $b_year) = explode('/', $b);

if ($a_year > $b_year ) return 1;
if ($a_year < $b_year ) return -1;

if ($a_month > $b_month) return 1;
if ($a_month < $b_month) return -1;

if ($a_day > $b_day ) return 1;
if ($a_day < $b_day ) return -1;

return 0;
}

$dates = array('12/14/2000', '08/10/2001', '08/07/1999');
usort($dates, 'date_sort');


배열 검색하기 


$favorite_foods = array(
1 => 'artichokes',
'bread',
'cauliflower',
'deviled eggs'
);
$food = 'cauliflower';
$position = array_search($food, $favorite_foods);

if ($position !== false) {
echo "My #$position favorite food is $food";
} else {
echo "Blech! I hate $food!";
}


함수 호출


function get_file($filename)
{
return file_get_contents($filename);
}

$function = 'get_file';
$filename = 'graphic.png';

// calls get_file('graphic.png')
call_user_func($function, $filename);

배열로 정의된  함수 호출

function get_file($filename)
{
return file_get_contents($filename);
}

function put_file($filename, $data)
{
return file_put_contents($filename, $data);
}

if ($action == 'get') {
$function = 'get_file';
$args = array('graphic.png');
} elseif ($action == 'put') {
$function = 'put_file';
$args = array('graphic.png', $graphic);
}

// calls get_file('graphic.png')
// calls put_file('graphic.png', $graphic)
call_user_func_array($function, $args);


Magic Overrrding

class Person {
// list person and email as valid properties
protected $data = array('person', 'email');

public function __get($property) {
if (isset($this->data[$property])) {
return $this->data[$property];
} else {
return null;
}
}

// enforce the restriction of only setting
// pre-defined properties
public function __set($property, $value) {
if (isset($this->data[$property])) {
$this->data[$property] = $value;
}
}

public function __isset($property) {
return isset($this->data[$property]);
}

public function __unset($property) {
if (isset($this->data[$property])) {
unset($this->data[$property]);
}
}
}


'웹개발 > Php' 카테고리의 다른 글

Apater 패턴 샘플  (0) 2017.02.06
추상팩토리 패턴 샘플 소스  (0) 2017.02.06
SQL 라이트 기본사용하기 ( Command Line Shell For SQLite)  (0) 2016.08.25
array_map 활용가이드  (0) 2016.08.10
php 기어맨 좋은자료  (0) 2016.06.02
댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함