본문 바로가기
PHP/생활코딩

5/25(2) 생활코딩

by SKim입니다 2020. 5. 25.

* 오늘의 진도

 PHP

  문자열 처리

 

18. 문자열 처리

(1) 문자열의 표기

 

(2) escaping

 

(3) 줄바꿈

단따옴표 안에서 \n을 하면 줄바꿈이 되는 것이 아니라 \n이 그대로 출력된다.

단따옴표는 그 안에 들어있는 데이터를 있는 그대로 해석하기 때문.

 

쌍따옴표는 해석의 과정을 거치기 때문에 속도가 약간 느리다.

 

 

(4) 문자열 안에서 변수 사용하기

단따옴표로  '생활코딩의 공식인사는 {$a[0]} {$a[1]}입니다'; 라고 쓰면 이렇게↓ 나와버린다.

만약에 단따옴표를 쓰고 싶다면 그림처럼 { }을 빼고 공백을 주고 .을 써줘야 한다.

.은 문자와 문자를 더해주는 역할을 하는 연산자이다.

 

 

(5) 문자와 문자를 더하기

cf) JavaScript에서는 숫자도 +가 되고 문자도 +가 되는데,

php는 문자와 숫자를 구분하기 때문에 여기서 +를 쓰면 에러가 발생한다.

 

 

(6) 문자와 관련된 함수

php는 다른 언어보다 문자와 관련해서 아주 풍부한 함수를 제공하고 있다.

= 문자 처리에 강점이 있다.

 

특히 JavaScript같은 경우는 문자와 관련된 부분이 별로 없기 때문에,

JavaScript했던 사람은 php를 해보면 아주 편리하다는 생각을 많이 갖게 된다.

 

 

① String position

http://docs.php.net/manual/kr/function.strpos.php

 

PHP: strpos - Manual

A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replaceme

docs.php.net

문자열이 처음 나타나는 위치를 찾는다.

인자로 세 개를 받을 수 있다.

[ ]는 옵션으로, 있어도 되고 없어도 되는 것이고

[ ]가 없는 것은 반드시 인자로 주어져야 하고, 주어지지 않으면 에러가 발생된다.

 

건초더미에서 바늘을 찾는다.

인자1) haystack - 건초더미

인자2) needle - 바늘

 

 

a가 문자열이 시작되는 첫번째 부분에 위치한다면, strpos이 0을 리턴할텐데,

보통 프로그래밍에서 0은 false를 의미하기 때문에,

===로 정확하게 비교해야 한다.

 

http://docs.php.net/manual/kr/function.implode.php

 

PHP: implode - Manual

It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys: 'four', 'five', '3rd' => 'six' );echo implode( ',', $a ),'/', implode( ',', $b );?>outputs:one,two,three/fou

docs.php.net

http://docs.php.net/manual/kr/function.explode.php

 

PHP: explode - Manual

As you can not send an enclosure value to explode, use str_getcsv,if you want to explode a string when the delimiter is in some cells. (Comma in quotes) a output using explode():\n";  print_r( explode(",",$a) );  print "\n";  print " b output using expl

docs.php.net

http://docs.php.net/manual/kr/function.htmlspecialchars.php

 

PHP: htmlspecialchars - Manual

The code I posted this morning (for giving back to htmlspecialchars etc. the old default ISO encoding) had some strange problem, didn't work if a page was reloaded! Here the code I came up with, without this problem: ")) {    runkit_function_copy('htmlsp

docs.php.net

 

'PHP > 생활코딩' 카테고리의 다른 글

5/26 생활코딩  (0) 2020.05.27
5/25(3) 생활코딩  (0) 2020.05.25
5/25 생활코딩 * 이미지 다루기 수강해야 함*  (0) 2020.05.25
5/24(4) 생활코딩 * Composer 나중에 보기 *  (0) 2020.05.24
5/24(3) 생활코딩  (0) 2020.05.24

댓글