Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
95
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

 

 

PHP and Regular Expressions

 

 

 

 

 

 

 

Matching Modifier

Description

 

 

 

 

S

Affects how a pattern is processed. If the S modifier is set, further

 

 

analysis of how best to process the regular expression takes place.

 

U

The U modifier alters the “greediness” behavior of patterns. With U

 

 

set, the default behavior becomes nongreedy (“lazy”). Matching

 

 

becomes greedy with (? ... ).

 

X

Turns on Perl-incompatible behavior.

 

e

Applies to preg_replace() function only.

 

 

 

Matching modifiers are written after the second of the paired or matched delimiters and immediately before the second of the paired double quote characters. So to match the pattern Hel case insensitively against the test string Hello world! using the preg_match() function, you would write the following:

preg_match(“/Hel/i”, “Hello world!”)

Several of these matching modifiers are used in examples later in the chapter.

Using the preg_match() Function

The preg_match() function attempts to match a pattern against a test string and is very similar to the ereg() function you used earlier. However, it is often faster than ereg() and so is to be preferred to ereg() when using versions of PHP that support PCRE functionality.

The preg_match() function can take two or three arguments. The first argument is a regular expression pattern. However, unlike ereg(), where you would write:

ereg(“Hel”, “Hello world!”);

to match the character sequence Hel in the string Hello world!, when you use the preg_match() function you must enclose the pattern in paired delimiters, such as paired forward slashes, inside the paired double quote characters. So when using preg_match(), you would write the following to match the character sequence Hel in Hello world!:

preg_match(“/Hel/”, Hello world!”);

The second argument is the test string. The optional third argument is a variable into which an array of groups will be returned, assuming that a match is found.

Try It Out

A preg_match() Example

1.Type the following code in a text editor:

<html>

<head>

<title>Simple preg_match() Regex Test</title> </head>

<body>

<?php

571

Chapter 23

if (preg_match(“/Hel/”, “Hello world!”)) echo “<p>A match was found.</p>” ?>

</body>

</html>

2.Save the code as C:\inetpub\wwwroot\PHP\SimplePregTest.php.

3.In Internet Explorer, enter the URL http://localhost/PHP/SimplePregTest.php, and inspect the displayed result, as shown in Figure 23-14. Because the pattern Hel is matched, the message A match was found. is displayed.

Figure 23-14

How It Works

The preg_match() function is used to produce a boolean value that can be tested in an if statement:

if (preg_match(“/Hel/”, “Hello world!”)) echo “<p>A match was found.</p>”

Notice that paired forward slashes are used as the delimiters for the regular expression pattern in the first argument of the preg_match() function:

The next example uses the preg_match() function with three arguments and manipulates the array elements specified in the third argument to the function. Array elements are numbered beginning at zero. Element [0] contains the whole match.

Try It Out

Using the preg_match() Function with Groups

1.Type the following code in a text editor:

<html>

<head>

<title>Using preg_match() with 3 arguments</title> </head>

<body>

<?php

$dateToday = gmdate(“Y m d”);

$myDate = preg_match(“/(\d{4})\s(\d{2}) (\d{2})/”, $dateToday, $dateComponents); if ($myDate)

{

572

PHP and Regular Expressions

echo “<p>The original date was: $dateToday</p>”; echo “<p>In MM/DD/YYYY format today is:

$dateComponents[2]/$dateComponents[3]/$dateComponents[1]</p>”;

}

?>

</body>

</html>

2.Save the code as C:\inetpub\wwwroot\PHP\preg_match_3args.php.

3.Type the URL http://localhost/PHP/preg_match_3args.php in Internet Explorer, and inspect the displayed results, as shown in Figure 23-15. The upper line of the Web page shows the original format of the date. The lower line shows the date expressed in MM/DD/YYYY format, with the new format being created using the $dateComponents array, which was created because $dateComponents was the third argument of the preg_match() function.

Figure 23-15

How It Works

The variable $dateToday is assigned a value returned from the gmdate() function. The arguments to the gmdate() function specify that the date is returned in YYYY MM DD format, with all values being expressed as numeric digits:

$dateToday = gmdate(“Y m d”);

The $myDate variable is assigned the value returned by the preg_match() function. Because there is a match for the pattern (\d{4})\s(\d{2}) (\d{2}) in the value of $dateToday, the $myDate variable holds the equivalent of the boolean value True. Notice that there is a space character between the second and third sets of paired parentheses.

The preg_match() function has three arguments, and the pattern in the first argument has groups created using parentheses. The $dateComponents variable is assigned array elements corresponding to each group created by the matched parentheses:

$myDate = preg_match(“/(\d{4})\s(\d{2}) (\d{2})/”, $dateToday, $dateComponents);

Because there is a match, the $myDate variable holds the value of True, so the statements contained in the if statement are executed:

if ($myDate)

573

Chapter 23

The original format of the date is displayed using the value of the $dateToday variable. The elements of the $dateComponents array are reordered to display the date in MM/DD/YYYY format:

{

echo “<p>The original date was: $dateToday</p>”; echo “<p>In MM/DD/YYYY format today is:

$dateComponents[2]/$dateComponents[3]/$dateComponents[1]</p>”;

}

The preg_match() function answers the question of whether or not a match is present. If you want to find and manipulate multiple matches (if they are present in the test string), you need to use the preg_match_all() function.

Using the preg_match_all() Function

The preg_match_all() function matches all character sequences in the test string that are matches for the specified regular expression.

Try It Out

Using the preg_match_all() Function

1.Type the following code in a text editor:

<html>

<head>

<title>Using preg_match_all()</title> </head>

<body>

<?php

$testString = “A99 B888 C234 D123 E45678 f2345”;

$myMatches = preg_match_all(“/[A-Z]\d{1,5}/”, $testString, $partNumbers); if ($myMatches)

{

for($counter=0; $counter < $myMatches; $counter++)

{

echo “<p>” . $partNumbers[0][$counter]. “</p>”;

}

}

?>

</body>

</html>

2.Save the code as C:\inetpub\wwwroot\PHP\preg_match_all.php.

3.In Internet Explorer, type the URL http://localhost/PHP/preg_match_all.php, and inspect the displayed results, as shown in Figure 23-16.

574

PHP and Regular Expressions

Figure 23-16

4.Edit the following line

$myMatches = preg_match_all(“/[A-Z]\d{1,5}/”, $testString, $partNumbers);

so that it matches case insensitively:

$myMatches = preg_match_all(“/[A-Z]\d{1,5}/i”, $testString, $partNumbers);

5.Save the amended code as C:\inetpub\wwwroot\PHP\preg_match_all_Insensitive.php.

6.Type the URL http://localhost/PHP/preg_match_all_Insensitive.php in Internet Explorer, and inspect the displayed results, as shown in Figure 23-17. Notice that there is an additional match displayed, f2345.

Figure 23-17

575