PHP 정규식

PHPz
풀어 주다: 2024-08-29 13:01:52
원래의
392명이 탐색했습니다.

정규식은 한 줄에 생성되는 패턴 일치 알고리즘으로 정의할 수 있습니다. 이는 유효성 검사 및 템플릿 인식의 경우 영향을 미칩니다. 메타 문자를 사용하면 사용자가 복잡한 패턴을 처리할 수 있습니다. 따라서 정규식에 대한 PHP 지원은 PHP 프로그래밍의 코드 품질을 향상시키는 데 도움이 됩니다. 모든 정규식은 주어진 주제 문자열에 대해 패턴 일치 기능을 제공하는 데 사용되는 일반 패턴 또는 문자 집합의 시퀀스입니다. RegExp 또는 RegEx라고도 합니다. 문자열 구문 분석에 사용되는 패턴 표기법 기반의 소형 프로그래밍 언어로도 간주됩니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

PHP 함수의 정규식 2세트

아래에서는 2가지 정규식 세트를 지원합니다.

  • POSIX 정규 표현식
  • PERL 스타일 정규 표현식

1. POSIX 정규 표현식

이것은 단일 문자가 입력 문자열과 일치해야 하는 문자 집합으로 정의됩니다. 이러한 표현식은 [] 내에 정의됩니다.

예:

  • [0-9]: 0에서 9까지의 모든 10진수 문자열을 필터링하도록 설계되었습니다.
  • [a-Z]: 소문자 'a'부터 대문자 'Z'까지 모든 문자를 필터링하도록 설계되었습니다.

필터를 더욱 구체적으로 만들기 위해 정규식 및 특수 문자를 포함하는 수량자라고 알려진 표준 구문이 개발되었습니다. 또한 빈도, 즉 괄호 문자 또는 문자 그룹의 발생 횟수나 인스턴스 및 수량에 대한 정보를 제공합니다.

다양한 수량자에 대한 설명을 확인할 수 있는 표:

Quantifier Description
S+ Filters out a string having at least one ‘s’.
S* Filters out a string having zero or more ‘s’.
S? Filters out a string having zero or one ‘s’.
S{N} Filters out a string having a sequence of N ‘s’.
S$ Filters out a string having ‘s’ at the end.
^S Filters out a string having ‘s’ at the beginning.
정량자

설명

S+ 's'가 하나 이상 포함된 문자열을 필터링합니다. S* 's'가 0개 이상인 문자열을 필터링합니다. S? 's'가 0개 또는 1개 있는 문자열을 필터링합니다. S{N} N개의 's' 시퀀스가 ​​있는 문자열을 필터링합니다. S$ 끝에 's'가 있는 문자열을 필터링합니다. ^S 처음에 's'가 있는 문자열을 필터링합니다. PHP는 사전 정의된 문자 범위/클래스와 관련된 일치 기능도 지원합니다.
predefined character class Description
[[:space:]] Filters out a string having a space.
[[:alpha:]] Filters out a string having alphabetic characters a-A through z-Z.
[[:digit:]] Filters out a string having numerical 0 to 9.
[[:alnum:]] Filters out a string having alphanumeric characters a-A through z-Z and numerical 0 to 9.
예: 사전 정의된 문자 클래스 설명 [[:space:]] 공백이 있는 문자열을 필터링합니다. [[:alpha:]] a-A부터 z-Z까지의 알파벳 문자가 포함된 문자열을 필터링합니다. [[:digit:]] 숫자 0~9의 문자열을 필터링합니다. [[:alnum:]] a-A부터 z-Z까지의 영숫자 문자와 0부터 9까지의 숫자를 포함하는 문자열을 필터링합니다.

POSIX 정규 표현식의 경우 PHP는 POSIX 스타일 정규 표현식을 사용하여 다양한 작업을 수행하기 위한 다양한 기능을 통합합니다.

아래 표와 같이 기능이 설명되어 있습니다.

POSIX Regex function Description
ereg() Used to search a string specified by or by pattern and to return true if the matching is found.
ereg_replace() Used to search a string specified by or by pattern and replace with replacement if the matching is found.
eregi() Used to perform non-case sensitive search for a string specified by or by pattern and to return true if the matching is found.
eregi_replace() Used to perform non-case sensitive for a string specified by or by pattern and replace with replacement if the matching is found.
split() Used to divide the string into separate elements based on boundaries that matches the searching pattern.
spliti() Used to perform non-case sensitive for the string to divide it into separate elements based on boundaries that matches the searching pattern.
sql_regcase() A utility function that convert each character from the input value into a bracketed expression making two characters.

2. PERL 스타일 정규 표현식

이 유형의 정규식 패턴은 POSIX 정규식과 유사하지만 메타 문자와 식별자로 생성됩니다. 이 Regexes의 구문은 POSIX 스타일과 호환됩니다.

아. 메타 문자: 특정 의미를 나타내는 백슬래시 뒤에 오는 알파벳 문자를 메타 문자라고 합니다.

PHP 스크립팅에서 지원되는 다양한 메타 문자가 있으며 아래 설명과 같이 Perl 유형 Regex로 사용됩니다.

Meta character Description
. Single character
d A digit character
D Non-digit character
s white space character e.g. SPACE, NEW LINE, TAB
S Non- white space character
w A word character
W Non-word character
[aeiou] Filters the matched character out of the given set
[^aeiou] Filters the unmatched character out of the given set
(set1|set2|set3) Filters the matched element that matches to any of the given alternatives
메타 문자

설명 . 단일 문자 디 숫자 디 숫자가 아닌 문자 s 공백 문자(예: 스페이스바, 새 줄, 탭 S 공백이 아닌 문자 여 단어 문자 W 비단어 문자 [aeiou] 주어진 세트에서 일치하는 문자를 필터링합니다 [^aeiou] 주어진 세트에서 일치하지 않는 문자를 필터링합니다 (세트1|세트2|세트3) 주어진 대안 중 하나와 일치하는 일치 요소를 필터링합니다

ㄴ. 수정자:

이러한 요소를 사용하면 사용자가 정규 표현식 작업에 추가적인 유연성을 사용할 수 있습니다.
Modifier Description
g Finds matchings globally.
cg Enable continue global search even after matching fails.
i Instructs to perform case insensitive search.
s Use the character ‘.’ to search for new line character.
m In case of input string containing new line or carriage return character, ‘^’ and ‘$’ are used to match for new line boundary.
x Permits to use white space to improve the clarity of the expression.
o Restrict the evaluation of the expression to occur only once.
아래 표에는 다양한 수정자와 해당 기능이 언급되어 있습니다. 수정자 설명 g 전역적으로 일치하는 항목을 찾습니다. cg 일치 실패 후에도 전역 검색 계속을 활성화합니다. 나는 대소문자를 구분하지 않고 검색하도록 지시합니다. s 새 줄 문자를 검색하려면 '.' 문자를 사용하세요. 미터 줄 바꾸기 또는 캐리지 리턴 문자가 포함된 입력 문자열의 경우 '^' 및 '$'를 사용하여 새 줄 경계를 일치시킵니다. x 표현의 명확성을 높이기 위해 공백 사용을 허용합니다. 아니 표현식의 평가가 한 번만 발생하도록 제한합니다.

POSIX 정규식 함수와 유사하게 PHP는 PERL 스타일 정규식과 호환되는 몇 가지 특정 함수도 제공합니다.

주요 기능 중 일부는 다음과 같습니다.

PERL style regexpcompitable function Description
preg_match() Return the first occurrence of the matching pattern.
preg_match_all() Return all occurrences of the matching pattern.
preg_split() Splits the string input into several elements based on the given regexp pattern as input.
Preg_quote() Used to quote the characters of the regex.
preg_grep() Used to find all the matching elements from array input.
preg_replace() Used to find matching element and replace it with the given replacement.

PHP 정규 표현식의 예

아래 예시는 애플리케이션을 보여줍니다

코드 조각은 입력 문자열을 스캔하고 주어진 Regex를 경계로 정의하여 주어진 입력을 여러 요소로 분할하도록 설계되었습니다.

코드:

<?php
// Declaring a regex
$regex = "([0-9]+)";
// Defining the input string
$inputstr = "String_a 1 String_b 2 String_c 3";
//Splitting the input string based on matching regex expression
$result = preg_split ($regex, $inputstr);
// Displaying result
echo $result[0];
echo "\n";
echo $result[1];
echo "\n";
echo $result[2];
echo "\n";
?>
로그인 후 복사

출력

preg_split() 함수는 '1', '2, '3' 요소가 경계로 표시되어 입력 문자열을 3부분으로 분할했습니다.

PHP 정규식

위 내용은 PHP 정규식의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!