วิธีใช้ preg_match() PHP (ภาษาอังกฤษ)

By | 14/02/2014

ต้องบอกก่อนว่า Copy มาจาก http://lzone.de/PHP%20preg_match%20Examples

เป็นความรู้ที่ดีมากๆ กลัวว่าวันหนึ่งอาจหายไปจาก lzone.de ขอเก็บเอาไว้เองหน่อยละกัน

PHP preg_match() Examples

Submitted by Lars Windolf on 20. October 2012 – 20:39
in

This post gives some simple examples for using regular expressions with preg_match() in PHP scripts.

1. Syntax of preg_match

While full syntax is

1
2
1
int preg_match ( string
1
$pattern
1
, string
1
$subject
1
     
1
[,
1
array
1
&
1
$matches
1
[, int
1
$flags
1
= 0 [, int
1
$offset
1
= 0 ]]] )

you propably will use preg_match() mostly with two parameters for simply matching checks or with three to extract matches.

You probably won’t use the 4th and 5th parameter which can be used to return match offsets and limit matching to a given offset in the string.

2. Simple String Checks with preg_match()

Here are some syntax examples that check strings for certain content:

Basic matching

1
2
3
4
5
1
preg_match(
1
"/PHP/"
1
,
1
"PHP"
1
)       # Match
1
for
1
an unbound literal
1
preg_match(
1
"/^PHP/"
1
,
1
"PHP"
1
)      # Match literal at start of string
1
preg_match(
1
"/PHP$/"
1
,
1
"PHP"
1
)      # Match literal at
1
end
1
of string
1
preg_match(
1
"/^PHP$/"
1
,
1
"PHP"
1
)     # Match
1
for
1
exact string content
1
preg_match(
1
"/^$/"
1
,
1
""
1
)           # Match
1
empty
1
string

Using different regex delimiters

1
2
3
1
preg_match(
1
"/PHP/"
1
,
1
"PHP"
1
)                # /
1
as
1
commonly used delimiter
1
preg_match(
1
"@PHP@"
1
,
1
"PHP"
1
)                # @
1
as
1
delimiter
1
preg_match(
1
"!PHP!"
1
,
1
"PHP"
1
)                # !
1
as
1
delimiter

Changing the delimiter becomes useful in some cases

1
2
1
preg_match(
1
"/http:\/\//"
1
,
1
"<a href="http://">http://</a>"
1
);     # match <a href="http://">http://</a> protocol prefix with / delimiter
1
preg_match(
1
"#<a href="http://">http://</a>#"
1
,  
1
"<a href="http://">http://</a>"
1
)      # match <a href="http://">http://</a> protocol prefix with # delimiter

Case sensitivity

1
2
1
preg_match(
1
"/PHP/"
1
,
1
"PHP"
1
)                #
1
case
1
sensitive string matching
1
preg_match(
1
"/php/i"
1
,
1
"PHP"
1
)               #
1
case
1
in-sensitive string matching

Matching with wildcards

1
2
3
4
5
6
1
preg_match(
1
"/P.P/"
1
,    
1
"PHP"
1
)            # match a single character
1
preg_match(
1
"/P.*P/"
1
,   
1
"PHP"
1
)            # match multipe characters
1
preg_match(
1
"/P[A-Z]P/"
1
,
1
"PHP"
1
)            # match from character range A-Z
1
preg_match(
1
"/[PH]*/"
1
,  
1
"PHP"
1
)            # match from character set P
1
and
1
H
1
preg_match(
1
"/P\wP/"
1
,   
1
"PHP"
1
)            # match one word character
1
preg_match(
1
"/\bPHP\b/"
1
,
1
"regex in PHP"
1
)   # match the word
1
"PHP"
1
, but not
1
"PHP"
1
as
1
larger string

Using quantifiers

1
2
3
4
1
preg_match(
1
"/[PH]{3}/"
1
,  
1
"PHP"
1
)          # match exactly 3 characters from set [PH]
1
preg_match(
1
"/[PH]{3,3}/"
1
,
1
"PHP"
1
)          # match exactly 3 characters from set [PH]
1
preg_match(
1
"/[PH]{,3}/"
1
1
"PHP"
1
)          # match at most 3 characters from set [PH]
1
preg_match(
1
"/[PH]{3,}/"
1
1
"PHP"
1
)          # match at least 3 characters from set [PH]

Note: all of the examples above should work (please comment if you find an error)!

3. Extracting Data with preg_match()

To extract data using regular expression we have to use capture/grouping syntax.

Some basic examples

1
2
3
4
5
6
7
8
1
# Extract everything after the literal
1
"START"
1
preg_match(
1
"/START(.*)/"
1
,
1
$string
1
,
1
$results
1
)  
1
# Extract the number from a
1
date
1
string
1
preg_match(
1
"/(\d{4})-(\d{2})-(\d{2})/"
1
,
1
"2012-10-20"
1
,
1
$results
1
)
1
# Nesting of capture groups, extract full name,
1
and
1
both parts...
1
preg_match(
1
"/name is ((\w+), (\w+))/"
1
,
1
"name is Doe, John"
1
,
1
$results
1
)

So you basically just enclose the sub patterns you want to extract with braces and fetch the results by passing a third parameter which preg_match() will fill as an array.

Named Capture Groups

1
2
1
# Extract the number from a
1
date
1
string
1
preg_match(
1
"/(?P&lt;year&gt;\d{4})-(?P&lt;month&gt;\d{2})-(?P&lt;day&gt;\d{2})/"
1
,
1
"2012-10-20"
1
,
1
$results
1
)

Now the $result array will additionally to the position matches 1, 2 and 3 contain the keys “year”, “month” and “day”. The advantage is never having to think of the capture positions anymore when you modify the expression!

4. Check for preg_match() Processing Errors!

While it might often be unimportant be aware that applying a regular expression might fail due to PCRE constraints. This usually happens when matching overly long strings or strings with faulty encoding.

The only way to notice that preg_match() was not able to check the string is by calling

1
1
preg_last_error()

Only if it returns PREG_NO_ERROR you got a safe result! Consider this when using preg_match() for security purposes.

Category: PHP

ใส่ความเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องที่ต้องการถูกทำเครื่องหมาย *