정규 표현식(Regex Expression)
PHP는 POSIX와 Perl(PCRE)이라는 두 가지 스타일의 정규 표현식을 지원한다. PHP 메뉴얼에 의하면 POSIX 스타일은 PHP 5.3.0부터 배제되었다고 경고하고 있으므로 Perl 스타일의 정규 표현식에 대해 강의하겠다.
- POSIX 스타일 : http://docs.php.net/manual/kr/ref.regex.php
- Perl 스타일 : http://docs.php.net/manual/kr/ref.pcre.php
들어가기 전에
아래는 정규표현식에서 사용되는 특수문자와 패턴이다. 최소한 아래 내용을 숙지하고 이 장을 공부해야 한다.
(마침표(.)가 잘 안보일수 있기 때문에 마침표만 작은 따옴표로 감싸 표현했다.)
문자열 찾기 : preg_match()
1 | int preg_match(string $pattern , string $subject [, array & $matches [, int $flags [, int $offset ]]]) |
subject에 pattern을 매칭시켜 그 결과값을 matches에 배열로 저장한다.
flags에 PREG_OFFSET_CAPTURE를 넘겨주면 "[0]->매칭된 문자열", "[1]->매칭된 문자열 시작 위치"를 갖는 배열로 반환한다. 이 배열은 matches의 [0]요소로 대입된다.(2차원 배열이 된다.)
offset은 subject에서 시작할 문자열의 위치(인덱스)이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php $subject = "abcdef" ; $pattern = '/^def/' ; ?> <?php preg_match( $pattern , $subject , $matches1 , PREG_OFFSET_CAPTURE, 3); preg_match( $pattern , substr ( $subject ,3), $matches2 , PREG_OFFSET_CAPTURE); preg_match( $pattern , substr ( $subject ,3), $matches3 ); print_r( $matches1 ); print_r( $matches2 ); print_r( $matches3 ); ?> /* 실행결과 $matches1 : Array ( ) // ^라는 특수기호 때문에 매칭되지 않는다. $matches2 : Array ( [0] => Array ( [0] => def [1] => 0 ) ) // 2차원 배열로 반환한다. $matches3 : Array ( [0] => def ) */ |
대소문자 무시
1 2 3 4 5 6 7 8 | <?php // 패턴 구분자 뒤의 "i"는 대소문자를 구별하지 않게 합니다. if (preg_match( "/php/i" , "PHP is the web scripting language of choice." )) { echo "발견하였습니다." ; // 실행 } else { echo "발견하지 못했습니다." ; } ?> |
예제 더보기 : http://docs.php.net/manual/kr/function.preg-match.php
preg_match_all() : http://docs.php.net/manual/kr/function.preg-match-all.php
문자열 교체하기 : preg_replace()
1 | mixed preg_replace(mixed $pattern , mixed $replacement , mixed $subject [, int $limit =-1[, int & $count ]]) |
subject에서 pattern에 매칭되는 문자열을 replacement로 바꾼다. 이 때, limit으로 개수를 제한할 수 있고 count에 바뀐 횟수를 저장할 수 있다.(limit의 기본값은 -1로 무제한을 의미한다.)
예제 더보기 : http://docs.php.net/manual/kr/function.preg-replace.php
문자열 분리하기 : preg_split()
1 | array preg_split(string $pattern , string $subject [,int $limit [, int $flags ]]) |
subject를 pattern에 따라 분리해 배열로 반환한다. flags의 사용법은 생각보다 복잡하다. 아래 링크에서 확인하자.
예제 더보기 : http://docs.php.net/manual/kr/function.preg-split.php