PHP 정규식
정규 표현식이란 무엇입니까?
정규식은 검색 패턴을 형성하는 일련의 문자입니다. 텍스트에서 데이터를 검색할 때 이 검색 패턴을 사용하여 검색하는 내용을 설명할 수 있습니다.
정규식은 단일 문자이거나 더 복잡한 패턴일 수 있습니다.
정규식은 모든 유형의 텍스트 검색 및 텍스트 바꾸기 작업을 수행하는 데 사용할 수 있습니다.
통사론
PHP에서 정규식은 구분 기호, 패턴 및 선택적 수정자로 구성된 문자열입니다.
$exp = "/w3schools/i";
위의 예에서 /
는 구분 기호 이고 w3schools 는 검색 중인 패턴 이며 검색을 대소문자를 구분하지 않도록 i
하는 수정자 입니다.
구분 기호는 문자, 숫자, 백슬래시 또는 공백이 아닌 모든 문자일 수 있습니다. 가장 일반적인 구분 기호는 슬래시(/)이지만 패턴에 슬래시가 포함되어 있으면 # 또는 ~와 같은 다른 구분 기호를 선택하는 것이 편리합니다.
정규식 함수
PHP는 정규식을 사용할 수 있는 다양한 기능을 제공합니다. ,
및 기능 preg_match()
은 가장 일반적으로 사용되는 기능 중 일부입니다.preg_match_all()
preg_replace()
Function | Description |
---|---|
preg_match() | Returns 1 if the pattern was found in the string and 0 if not |
preg_match_all() | Returns the number of times the pattern was found in the string, which may also be 0 |
preg_replace() | Returns a new string where matched patterns have been replaced with another string |
preg_match() 사용
이 preg_match()
함수는 문자열에 패턴과 일치하는 항목이 포함되어 있는지 여부를 알려줍니다.
예시
정규식을 사용하여 문자열에서 "w3schools"에 대해 대소문자를 구분하지 않는 검색을 수행합니다.
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo
preg_match($pattern, $str); // Outputs 1
?>
preg_match_all() 사용
이 preg_match_all()
함수는 문자열의 패턴에 대해 몇 개의 일치 항목이 발견되었는지 알려줍니다.
예시
정규식을 사용하여 문자열에서 "ain"의 발생 횟수를 대소문자를 구분하지 않고 계산합니다.
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
preg_replace() 사용
이 preg_replace()
함수는 문자열에서 패턴의 모든 일치 항목을 다른 문자열로 바꿉니다.
예시
대소문자를 구분하지 않는 정규식을 사용하여 문자열에서 Microsoft를 W3Schools로 바꿉니다.
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo
preg_replace($pattern, "W3Schools", $str); // Outputs "Visit
W3Schools!"
?>
정규식 수정자
수정자는 검색 수행 방법을 변경할 수 있습니다.
Modifier | Description |
---|---|
i | Performs a case-insensitive search |
m | Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line) |
u | Enables correct matching of UTF-8 encoded patterns |
정규 표현식 패턴
대괄호는 문자 범위를 찾는 데 사용됩니다.
Expression | Description |
---|---|
[abc] | Find one character from the options between the brackets |
[^abc] | Find any character NOT between the brackets |
[0-9] | Find one character from the range 0 to 9 |
메타 문자
메타 문자는 특별한 의미를 가진 문자입니다.
Metacharacter | Description |
---|---|
| | Find a match for any one of the patterns separated by | as in: cat|dog|fish |
. | Find just one instance of any character |
^ | Finds a match as the beginning of a string as in: ^Hello |
$ | Finds a match at the end of the string as in: World$ |
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
수량자
수량자는 수량을 정의합니다.
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
n{x} | Matches any string that contains a sequence of X n's |
n{x,y} | Matches any string that contains a sequence of X to Y n's |
n{x,} | Matches any string that contains a sequence of at least X n's |
참고: 표현식에서 특수 문자 중 하나를 검색해야 하는 경우 백슬래시( \ )를 사용하여 특수 문자를 이스케이프할 수 있습니다. 예를 들어, 하나 이상의 물음표를 검색하려면 다음 표현식을 사용할 수 있습니다. $pattern = '/\?+/';
그룹화
괄호 ( )
를 사용하여 전체 패턴에 수량자를 적용할 수 있습니다. 또한 일치 항목으로 사용할 패턴 부분을 선택하는 데 사용할 수도 있습니다.
예시
그룹화를 사용하여 ba 다음에 두 개의 na 인스턴스를 찾아 "banana"라는 단어를 검색합니다 .
<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo
preg_match($pattern, $str); // Outputs 1
?>
완전한 RegExp 참조
전체 참조를 보려면 전체 PHP 정규식 참조로 이동하십시오 .
참조에는 모든 정규식 함수에 대한 설명과 예가 포함되어 있습니다.