PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

패턴 변경자> <pcntl_wtermsig
Last updated: Sun, 25 Nov 2007

view this page in

정규표현식 함수 (펄-호환)

소개

이 함수들에서 사용되는 패턴 문법은 펄에 가깝습니다. 표현식은 구분자로 감싸주어야 합니다. 예를 들면, 슬래쉬(/)로 감싸줍니다. 영문자와 숫자, 백슬래쉬(\)를 제외한 어떠한 문자라도 구분자로 사용할 수 있습니다. 구분자가 표현식 안에서 사용될 경우, 백슬래쉬로 이스케이프해야합니다. PHP 4.0.4부터, 펄 형식의 (), {}, [], <> 매칭 구분자를 사용할 수 있습니다. 자세한 설명은 패턴 문법을 참고하십시오.

종료 구분자 뒤에는 매칭에 영향을 주는 여러가지 변경자(midifier)를 쓸 수 있습니다. 패턴 변경자를 참고하십시오.

PHP는 POSIX 확장 정규표현식 함수로 POSIX 확장 문법을 사용하는 정규표현식을 지원합니다.

Warning

PCRE의 몇몇 제한에 주의를 해야합니다. 자세한 정보는 » http://www.pcre.org/pcre.txt을 참고하십시오.

요구 조건

정규표현식 지원은 Philip Hazel이 작성한 PCRE 라이브러리 패키지에 의해 제공됩니다. 저작권은 University of Cambridge, England에 있습니다. » ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/에 존재합니다.

설치

PHP 4.2.0부터 이 함수들은 기본값으로 사용 가능합니다. --without-pcre-regex로 PCRE 함수를 사용하지 않을 수 있습니다. 번들된 라이브러리를 사용하지 않는다면, --with-pcre-regex=DIR을 이용하여 PCRE의 인크루드와 라이브러리 파일이 있는 특정한 디렉토리를 지정하십시오. 이전 버전에서는 이 함수들을 사용하기 위해서는 PHP를 --with-pcre-regex[=DIR]를 주어서 설정하고 컴파일해야합니다.

PHP 윈도우 버전에서는 이 확장에 대한 지원이 포함되어 있습니다. 이 함수들을 이용하기 위해서 추가로 확장을 읽어들일 필요가 없습니다.

실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.

자원형

이 확장은 리소스형을 정의하지 않습니다.

예약 상수

이 확장은 다음의 상수들을 정의합니다. 이 확장을 PHP에 내장했거나, 실행시에 동적으로 읽어들일 경우에만 사용할 수 있습니다.

PREG 상수
상수 설명
PREG_PATTERN_ORDER $matches[0] 배열은 패턴 전체를 가지고, $matches[1] 배열이 처음 괄호에 들은 서브패턴의 문자열을 가지도록 결과를 지정합니다. 이 플래그는 preg_match_all()에서만 사용합니다.
PREG_SET_ORDER $matches[0] 배열은 매치된 첫번째 집합을 가지고, $matches[1]는 두번째 집합을 가지도록 결과를 지정합니다. 이 플래그는 preg_match_all()에서만 사용합니다.
PREG_OFFSET_CAPTURE PREG_SPLIT_OFFSET_CAPTURE의 설명을 보십시오. 이 플래그는 PHP 4.3.0부터 사용할 수 있습니다.
PREG_SPLIT_NO_EMPTY 이 플래그는 preg_split()가 비어있지 않은 조각만을 반환하게 합니다.
PREG_SPLIT_DELIM_CAPTURE 이 플래그는 preg_split()가 구분자 안의 괄호로 둘러싸인 표현식도 잡아내게 합니다. PHP 4.0.5부터 사용할 수 있습니다.
PREG_SPLIT_OFFSET_CAPTURE 이 플래그를 설정하면, 매치하는 모든 문자열 요소의 시작 위치를 함께 반환합니다. 매치된 문자열을 0으로, 문자열 시작 위치를 1로 가지는 배열을 원소로 가지는 배열을 반환합니다. 이 플래그는 PHP 4.3.0부터 사용할 수 있고, preg_split()에서만 사용합니다.

예제

Example#1 유효한 패턴 예제

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Example#2 유효하지 않은 패턴 예제

  • /href='(.*)' - 종료 구분자가 없습니다
  • /\w+\s*\w+/J - 알 수 없는 변경자 'J'
  • 1-\d3-\d3-\d4| - 시작 구분자가 없습니다

Table of Contents

  • 패턴 변경자 — 정규표현식 패턴에 존재하는 변경자의 설명
  • 패턴 문법 — PCRE 정규표현식 문법 설명
  • preg_grep — 패턴 매치의 배열을 반환합니다.
  • preg_last_error — Returns the error code of the last PCRE regex execution
  • preg_match_all — 전역 정규 표현식 매치를 수행합니다.
  • preg_match — 정규표현식 매치를 수행합니다.
  • preg_quote — 정규 표현식 문자를 인용합니다.
  • preg_replace_callback — 콜백을 이용한 정규 표현식 검색과 치환을 수행합니다.
  • preg_replace — 정규 표현식 검색과 치환을 수행합니다.
  • preg_split — 정규 표션식에 따라 문자열을 나눕니다.


패턴 변경자> <pcntl_wtermsig
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
PCRE
stronk7 at moodle dot org
13-Sep-2007 01:42
One comment about 5.2.x and the pcre.backtrack_limit:

Note that this setting wasn't present under previous PHP releases and the behaviour (or limit) under those releases was, in practise,  higher so all these PCRE functions were able to "capture" longer strings.

With the arrival of the setting, defaulting to 100000 (less than 100K), you won't be able to match/capture strings over that size using, for example "ungreedy" modifiers.

So, in a lot of situations, you'll need to raise that (very small IMO) limit.

The worst part is that PHP simply won't match/capture those strings over pcre.backtrack_limit and will it be 100% silent about that (I think that throwing some NOTICE/WARNING if raised could help a lot to developers).

There is a lot of people suffering this changed behaviour from I've read on forums, bugs and so on).

Hope this note helps, ciao :-)
misc at e2007 dot cynergi dot com
05-May-2007 04:16
PCRE faster than POSIX RE? Not always.

In a recent search-engine project here at Cynergi, I had a simple loop with a few cute ereg_replace() functions that took 3min to process data. I changed that 10-line loop into a 100-line hand-written code for replacement and the loop now took 10s to process the same data! This opened my eye to what can *IN SOME CASES* be very slow regular expressions.

Lately I decided to look into Perl-compatible regular expressions (PCRE). Most pages claim PCRE are faster than POSIX, but a few claim otherwise. I decided on bechmarks of my own.

My first few tests confirmed PCRE to be faster, but... the results were slightly different than others were getting, so I decided to benchmark every case of RE usage I had on a 8000-line secure (and fast) Webmail project here at Cynergi to check it out.

The results? Inconclusive! Sometimes PCRE *are* faster (sometimes by a factor greater than 100x faster!), but some other times POSIX RE are faster (by a factor of 2x).

I still have to find a rule on when are one or the other faster. It's not only about search data size, amount of data matched, or "RE compilation time" which would show when you repeated the function often: one would *always* be faster than the other. But I didn't find a pattern here. But truth be said, I also didn't take the time to look into the source code and analyse the problem.

I can give you some examples, though. The POSIX RE

([0-9]{4})/([0-9]{2})/([0-9]{2})[^0-9]+
([0-9]{2}):([0-9]{2}):([0-9]{2})

is 30% faster in POSIX than when converted to PCRE (even if you use \d and \D and non-greedy matching). On the other hand, a similarly PCRE complex pattern

/[0-9]{1,2}[ \t]+[a-zA-Z]{3}[ \t]+[0-9]{4}[ \t]+[0-9]{1,2}:[0-9]{1,2}(:[0-9]{1,2})?[ \t]+[+-][0-9]{4}/

is 2.5x faster in PCRE than in POSIX RE. Simple replacement patterns like

ereg_replace( "[^a-zA-Z0-9-]+", "", $m );

are 2x faster in POSIX RE than PCRE. And then we get confused again because a POSIX RE pattern like

(^|\n|\r)begin-base64[ \t]+[0-7]{3,4}[ \t]+......

is 2x faster as POSIX RE, but the case-insensitive PCRE

/^Received[ \t]*:[ \t]*by[ \t]+([^ \t]+)[ \t]/i

is 30x faster than its POSIX RE version!

When it comes to case sensitivity, PCRE has so far seemed to be the best option. But I found some really strange behaviour from ereg/eregi. On a very simple POSIX RE

(^|\r|\n)mime-version[ \t]*:

I found eregi() taking 3.60s (just a number in a test benchmark), while the corresponding PCRE took 0.16s! But if I used ereg() (case-sensitive) the POSIX RE time went down to 0.08s! So I investigated further. I tried to make the POSIX RE case-insensitive itself. I got as far as this:

(^|\r|\n)[mM][iI][mM][eE]-vers[iI][oO][nN][ \t]*:

This version also took 0.08s. But if I try to apply the same rule to any of the 'v', 'e', 'r' or 's' letters that are not changed, the time is back to the 3.60s mark, and not gradually, but immediatelly so! The test data didn't have any "vers" in it, other "mime" words in it or any "ion" that might be confusing the POSIX parser, so I'm at a loss.

Bottom line: always benchmark your PCRE / POSIX RE to find the fastest!

Tests were performed with PHP 5.1.2 under Windows, from the command line.

Pedro Freire
cynergi.com
richardh at phpguru dot org
22-Sep-2005 11:50
There's a printable PDF PCRE cheat sheet available here:

http://www.phpguru.org/article.php?ne_id=67

Has the common metacharacters, quantifiers, pattern modifiers, character classes and assertions with short explanations.
Ned Baldessin
23-Oct-2004 06:08
If you want to perform regular expressions on Unicode strings, the PCRE functions will NOT be of any help. You need to use the Multibyte extension : mb_ereg(), mb_eregi(), pb_ereg_replace() and so on. When doing so, be carefull to set the default text encoding to the same encoding used by the text you are searching and replacing in. You can do that with the mb_regex_encoding() function. You will probably also want to set the default encoding for the other mb_* string functions with mb_internal_encoding().

So when dealing with, say, french text, I start with these :
<?php
mb_internal_encoding
('UTF-8');
mb_regex_encoding('UTF-8');
setlocale(LC_ALL, 'fr-fr');
?>
steve at stevedix dot de
20-Jul-2004 05:17
Something to bear in mind is that regex is actually a declarative programming language like prolog : your regex is a set of rules which the regex interpreter tries to match against a string.   During this matching, the interpreter will assume certain things, and continue assuming them until it comes up against a failure to match, which then causes it to backtrack.  Regex assumes "greedy matching" unless explicitly told not to, which can cause a lot of backtracking.  A general rule of thumb is that the more backtracking, the slower the matching process.

It is therefore vital, if you are trying to optimise your program to run quickly (and if you can't do without regex), to optimise your regexes to match quickly.

I recommend the use of a tool such as "The Regex Coach" to debug your regex strings.

http://weitz.de/files/regex-coach.exe (Windows installer) http://weitz.de/files/regex-coach.tgz (Linux tar archive)

패턴 변경자> <pcntl_wtermsig
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites