찾다
백엔드 개발PHP 튜토리얼Getting Started with PHP Regular Expressions

[ Note: Have you already pre-ordered your copy of our  Printed Smashing Book #3? The book is a professional guide on how to redesign websites and it also introduces a whole new mindset for progressive Web design, written by experts for you.]

1. What are Regular Expressions

The main purpose of regular expressions, also called regex or regexp, is to efficiently search for patterns in a given text. These search patterns are written using a special format which a regular expression parser understands.

 

Regular expressions are originating from Unix systems, where a program was designed, called grep, to help users work with strings and manipulate text. By following a few basic rules, one can create very complex search patterns.

As an example, let’s say you’re given the task to check wether an e-mail or a telephone number has the correct form. Using a few simple commands these problems can easily be solved thanks to regular expressions. The syntax doesn’t always seems straightforward at first, but once you learn it, you’ll realize that you can do pretty complex searches easily, just by typing in a few characters and you’ll approach problems from a different perspective.

2. Perl Compatible Regular Expressions

PHP has implemented quite a few regex functions which uses different parsing engines. There are two major parser in PHP. One called POSIX and the other PCRE or Perl Compatible Regular Expression.

The PHP function prefix for POSIX is ereg_. Since the release of PHP 5.3 this engine is deprecated, but let’s have a look at the more optimal and faster PCRE engine.

In PHP every PCRE function starts with preg_ such as preg_match or preg_replace. You can read the full function list in PHP’s documentation.

3. Basic Syntax

To use regular expressions first you need to learn the syntax. This syntax consists in a series of letters, numbers, dots, hyphens and special signs, which we can group together using different parentheses.

In PHP every regular expression pattern is defined as a string using the Perl format. In Perl, a regular expression pattern is written between forward slashes, such as /hello/. In PHP this will become a string, ‘/hello/’.

Now, let’s have a look at some operators, the basic building blocks of regular expressions

Operator Description
^ The circumflex symbol marks the beginning of a pattern, although in some cases it can be omitted
$ Same as with the circumflex symbol, the dollar sign marks the end of a search pattern
. The period matches any single character
? It will match the preceding pattern zero or one times
+ It will match the preceding pattern one or more times
* It will match the preceding pattern zero or more times
| Boolean OR
- Matches a range of elements
() Groups a different pattern elements together
[] Matches any single character between the square brackets
{min, max} It is used to match exact character counts
\d Matches any single digit
\D Matches any single non digit caharcter
\w Matches any alpha numeric character including underscore (_)
\W Matches any non alpha numeric character excluding the underscore character
\s Matches whitespace character

As an addition in PHP the forward slash character is escaped using the simple slash \. Example: ‘/he\/llo/’

To have a brief understanding how these operators are used, let’s have a look at a few examples:

Example Description
‘/hello/’ It will match the word hello
‘/^hello/’ It will match hello at the start of a string. Possible matches are hello orhelloworld, but not worldhello
‘/hello$/’ It will match hello at the end of a string.
‘/he.o/’ It will match any character between he and o. Possible matches are heloor heyo, but not hello
‘/he?llo/’ It will match either llo or hello
‘/hello+/’ It will match hello on or more time. E.g. hello or hellohello
‘/he*llo/’ Matches llo, hello or hehello, but not hellooo
‘/hello|world/’ It will either match the word hello or world
‘/(A-Z)/’ Using it with the hyphen character, this pattern will match every uppercase character from A to Z. E.g. A, B, C…
‘/[abc]/’ It will match any single character a, b or c
‘/abc{1}/’ Matches precisely one c character after the characters ab. E.g. matchesabc, but not abcc
‘/abc{1,}/’ Matches one or more c character after the characters ab. E.g. matches abcor abcc
‘/abc{2,4}/’ Matches between two and four c character after the characters ab. E.g. matches abcc, abccc or abcccc, but not abc

Besides operators, there are regular expression modifiers, which can globally alter the behavior of search patterns.

The regex modifiers are placed after the pattern, like this ‘/hello/i’ and they consists of single letters such as i which marks a pattern case insensitive or x which ignores white-space characters. For a full list of modifiers please visit PHP’s online documentation.

The real power of regular expressions relies in combining these operators and modifiers, therefore creating rather complex search patterns.

4. Using Regex in PHP

In PHP we have a total of nine PCRE functions which we can use. Here’s the list:

preg_filter ? performs a regular expression search and replace preg_grep ? returns array entries that match a pattern preg_last_error ? returns the error code of the last PCRE regex execution preg_match ? perform a regular expression match preg_match_all ? perform a global regular expression match preg_quote ? quote regular expression characters preg_replace ? perform a regular expression search and replace preg_replace_callback ? perform a regular expression search and replace using a callback preg_split ? split string by a regular expression

The two most commonly used functions are preg_match and preg_replace.

Let’s begin by creating a test string on which we will perform our regular expression searches. The classical hello world should do it.

view plain copy to clipboard print ?

$test_string = 'hello world';  

If we simply want to search for the word hello or world then the search pattern would look something like this:

view plain copy to clipboard print ?

preg_match('/hello/', $test_string);   preg_match('/world/', $test_string);  

If we wish to see if the string begins with the word hello, we would simply put the ^ character in the beginning of the search pattern like this:

view plain copy to clipboard print ?

preg_match('/^hello/', $test_string);  

Please note that regular expressions are case sensitive, the above pattern won’t match the word hElLo. If we want our pattern to be case insensitive we should apply the following modifier:

view plain copy to clipboard print ?

preg_match('/^hello/i', $test_string);  

Notice the character i at the end of the pattern after the forward slash.

Now let’s examine a more complex search pattern. What if we want to check that the first five characters in the string are alpha numeric characters.

view plain copy to clipboard print ?

preg_match('/^[A-Za-z0-9]{5}/', $test_string);  

Let’s dissect this search pattern. First, by using the caret character (^) we specify that the string must begin with an alpha numeric character. This is specified by [A-Za-z0-9].

A-Z means all the characters from A to Z followed by a-z which is the same except for lowercase character, this is important, because regular expressions are case sensitive. I think you’ll figure out by yourself what 0-9 means.

{5} simply tells the regex parser to count exactly five characters. If we put six instead of five, the parser wouldn’t match anything, because in our test string the word hello is five characters long, followed by a white-space character which in our case doesn’t count.

Also, this regular expression could be optimized to the following form:

view plain copy to clipboard print ?

preg_match('/^\w{5}/', $test_string);  

\w specifies any alpha numeric characters plus the underscore character (_).

6. Useful Regex Functions

Here are a few PHP functions using regular expressions which you could use on a daily basis.

Validate e-mail. This function will validate a given e-mail address string to see if it has the correct form.

view plain copy to clipboard print ?

function validate_email($email_address)   {       if( !preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+                       ([a-zA-Z0-9\._-]+)+$/", $email_address))       {           return false;       }       return true;   }  

Validate a URL

view plain copy to clipboard print ?

function validate_url($url)   {       return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?                        (/.*)?$|i', $url);   }  

Remove repeated words. I often found repeated words in a text, such as this this. This handy function will remove such duplicate words.

view plain copy to clipboard print ?

function remove_duplicate_word($text)   {       return preg_replace("/s(w+s)1/i", "$1", $text);   }  

Validate alpha numeric, dashes, underscores and spaces

view plain copy to clipboard print ?

function validate_alpha($text)   {       return preg_match("/^[A-Za-z0-9_- ]+$/", $text);   }  

Validate US ZIP codes

view plain copy to clipboard print ?

function validate_zip($zip_code)   {       return preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code);   }   7. Regex Cheat Sheet

Because cheat sheets are cool nowadays, below you can find a PCRE cheat sheet that you can run through quickly anytime you forget something.

Meta Characters   Description
^ Marks the start of a string
$ Marks the end of a string
. Matches any single character
| Boolean OR
() Group elements
[abc] Item in range (a,b or c)
[^abc] NOT in range (every character except a,b or c)
\s White-space character
a? Zero or one b characters. Equals to a{0,1}
a* Zero or more of a
a+ One or more of a
a{2} Exactly two of a
a{,5} Up to five of a
a{5,10} Between five to ten of a
\w Any alpha numeric character plus underscore. Equals to [A-Za-z0-9_]
\W Any non alpha numeric characters
\s Any white-space character
\S Any non white-space character
\d Any digits. Equals to [0-9]
\D Any non digits. Equals to [^0-9]
Pattern Modifiers   Description
i Ignore case
m Multiline mode
S Extra analysis of pattern
u Pattern is treated as UTF-8
8. Useful Readings 15 PHP Regular Expression for Web Developers Mastering Regular Expressions in PHP Introduction to PHP Regex

Author: Joel Reyes

Joel Reyes Has been designing and coding web sites for several years, this has lead him to be the creative mind behind Looney Designer a design resource and portfolio site that revolves around web and graphic design.

 

From: http://www.noupe.com/php/php-regular-expressions.html

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP 세션이 실패 할 수있는 몇 가지 일반적인 문제는 무엇입니까?PHP 세션이 실패 할 수있는 몇 가지 일반적인 문제는 무엇입니까?Apr 25, 2025 am 12:16 AM

phpsession 실패 이유에는 구성 오류, 쿠키 문제 및 세션 만료가 포함됩니다. 1. 구성 오류 : 올바른 세션을 확인하고 설정합니다. 2. 쿠키 문제 : 쿠키가 올바르게 설정되어 있는지 확인하십시오. 3. 세션 만료 : 세션 시간을 연장하기 위해 세션을 조정합니다 .GC_MAXLIFETIME 값을 조정하십시오.

PHP의 세션 관련 문제를 어떻게 디버그합니까?PHP의 세션 관련 문제를 어떻게 디버그합니까?Apr 25, 2025 am 12:12 AM

PHP에서 세션 문제를 디버그하는 방법 : 1. 세션이 올바르게 시작되었는지 확인하십시오. 2. 세션 ID의 전달을 확인하십시오. 3. 세션 데이터의 저장 및 읽기를 확인하십시오. 4. 서버 구성을 확인하십시오. 세션 ID 및 데이터를 출력, 세션 파일 컨텐츠보기 등을 통해 세션 관련 문제를 효과적으로 진단하고 해결할 수 있습니다.

session_start ()가 여러 번 호출되면 어떻게됩니까?session_start ()가 여러 번 호출되면 어떻게됩니까?Apr 25, 2025 am 12:06 AM

Session_Start ()로 여러 통화를하면 경고 메시지와 가능한 데이터 덮어 쓰기가 발생합니다. 1) PHP는 세션이 시작되었다는 경고를 발행합니다. 2) 세션 데이터의 예상치 못한 덮어 쓰기를 유발할 수 있습니다. 3) Session_status ()를 사용하여 반복 통화를 피하기 위해 세션 상태를 확인하십시오.

PHP에서 세션 수명을 어떻게 구성합니까?PHP에서 세션 수명을 어떻게 구성합니까?Apr 25, 2025 am 12:05 AM

SESSION.GC_MAXLIFETIME 및 SESSION.COOKIE_LIFETIME을 설정하여 PHP에서 세션 수명을 구성 할 수 있습니다. 1) SESSION.GC_MAXLIFETIME 서버 측 세션 데이터의 생존 시간을 제어합니다. 2) 세션 .Cookie_Lifetime 클라이언트 쿠키의 수명주기를 제어합니다. 0으로 설정하면 브라우저가 닫히면 쿠키가 만료됩니다.

세션을 저장하기 위해 데이터베이스를 사용하면 어떤 장점이 있습니까?세션을 저장하기 위해 데이터베이스를 사용하면 어떤 장점이 있습니까?Apr 24, 2025 am 12:16 AM

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

PHP에서 사용자 정의 세션 처리를 어떻게 구현합니까?PHP에서 사용자 정의 세션 처리를 어떻게 구현합니까?Apr 24, 2025 am 12:16 AM

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

세션 ID 란 무엇입니까?세션 ID 란 무엇입니까?Apr 24, 2025 am 12:13 AM

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

무국적 환경 (예 : API)에서 세션을 어떻게 처리합니까?무국적 환경 (예 : API)에서 세션을 어떻게 처리합니까?Apr 24, 2025 am 12:12 AM

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 ​​있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구