PHP 튜토리얼

PHP 홈 PHP 소개 PHP 설치 PHP 구문 PHP 주석 PHP 변수 PHP 에코 / 인쇄 PHP 데이터 유형 PHP 문자열 PHP 숫자 PHP 수학 PHP 상수 PHP 연산자 PHP If...Else...Elseif PHP 스위치 PHP 루프 PHP 함수 PHP 배열 PHP 슈퍼글로벌 PHP 정규식

PHP 양식

PHP 양식 처리 PHP 양식 유효성 검사 PHP 양식 필요 PHP 양식 URL/이메일 PHP 양식 완성

PHP 고급

PHP 날짜 및 시간 PHP 포함 PHP 파일 처리 PHP 파일 열기/읽기 PHP 파일 생성/쓰기 PHP 파일 업로드 PHP 쿠키 PHP 세션 PHP 필터 PHP 필터 고급 PHP 콜백 함수 PHP JSON PHP 예외

PHP OOP

PHP OOP란? PHP 클래스/객체 PHP 생성자 PHP 소멸자 PHP 액세스 수정자 PHP 상속 PHP 상수 PHP 추상 클래스 PHP 인터페이스 PHP 특성 PHP 정적 메서드 PHP 정적 속성 PHP 네임스페이스 PHP 반복 가능

MySQL 데이터베이스

MySQL 데이터베이스 MySQL 연결 MySQL 생성 DB MySQL 테이블 생성 MySQL 삽입 데이터 MySQL 마지막 ID 가져오기 MySQL은 다중 삽입 MySQL 준비 MySQL 선택 데이터 MySQL 어디 MySQL 주문 기준 MySQL 데이터 삭제 MySQL 업데이트 데이터 MySQL 제한 데이터

PHP XML

PHP XML 파서 PHP SimpleXML 파서 PHP SimpleXML - 가져오기 PHP XML 국외 거주자 PHP XML DOM

PHP - AJAX

AJAX 소개 AJAX PHP AJAX 데이터베이스 AJAX XML AJAX 라이브 검색 AJAX 투표

PHP 예제

PHP 예제 PHP 컴파일러 PHP 퀴즈 PHP 연습 PHP 인증서

PHP 참조

PHP 개요 PHP 배열 PHP 캘린더 PHP 날짜 PHP 디렉토리 PHP 오류 PHP 예외 PHP 파일 시스템 PHP 필터 PHP FTP PHP JSON PHP 키워드 PHP 라이브러리 XML PHP 메일 PHP 수학 PHP 기타 PHP MySQLi PHP 네트워크 PHP 출력 제어 PHP 정규식 PHP SimpleXML PHP 스트림 PHP 문자열 PHP 변수 처리 PHP XML 파서 PHP 우편번호 PHP 시간대

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 정규식 참조로 이동하십시오 .

참조에는 모든 정규식 함수에 대한 설명과 예가 포함되어 있습니다.