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

Chapter 23

How It Works

The test string is assigned to the variable $testString:

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

The $myMatches variable is assigned the int value returned from the preg_match_all() function. You will use the value of the $myMatches variable when looping through array values a little later.

The $partNumbers variable is the third argument of the preg_match_all() function and is assigned an array of matches:

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

To display all the results, use an if statement with a for loop nested inside it. The test of the if statement is whether $myMatches is unequal to 0; in other words, if there is at least one match, the test for the if statement returns True:

if ($myMatches)

{

The for loop starts at 0 and counts up to the value of the $myMatches variable:

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

{

The echo statement is used to concatenate literal text with the value of an array element, determined by $counter and a further piece of literal text.

You want to return the whole match, so use element 0 for each match The other dimension of the array is determined by the current value of the $counter variable:

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

}

At Step 4, the pattern [A-Z]\d{1,5} is matched. This matches any character sequence where an uppercase alphabetic character is followed by between one and five numeric digits. The default matching is case sensitive. Therefore, the matches are A99, B888, C234, D123, and E45678 (as displayed in Figure 23-16).

After you edit the first argument of the preg_match_all() function to “/[A-Z]\d{1,5}/i”, matching is case insensitive. Now the pattern [A-Z]\d{1,5} matches an alphabetic character of either case followed by between one and five numeric digits. All the previous matches still match. In addition, there is a match f2345, which has a lowercase alphabetic character.

Using the preg_grep() Function

The preg_grep() function matches a regular expression pattern against the elements in an array. The preg_grep() function takes two arguments. The first argument is a regular expression pattern. The second argument is an array.

576

PHP and Regular Expressions

So to assign the matches in an array $myArray for a pattern $myPattern to a variable $myMatches, you would write the following:

$myMatches = preg_grep($myPattern, $myArray);

Try It Out

Using the preg_grep() Function

1.Type the following code in a text editor:

<html>

<head>

<title>A preg_grep() Test</title> </head>

<body>

<?php

$myArray = array(“Hello”, “Help”, “helper”, “shell”, “satchel”, “Camera”); $myMatchesSensitive = preg_grep(“/Hel/”, $myArray);

echo “<p>Matching case sensitively:</p>”; if ($myMatchesSensitive)

{

print_r (array_values($myMatchesSensitive));

}

$myMatchesInsensitive = preg_grep(“/Hel/i”, $myArray); echo “<br /><p>Matching case insensitively:</p>”;

if ($myMatchesInsensitive)

{

print_r (array_values($myMatchesInsensitive));

}

?>

</body>

</html>

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

3.In Internet Explorer, enter the URL http://localhost/PHP/preg_grep.php, and inspect the displayed results, as shown in Figure 23-18. Compare the matches with case-sensitive and caseinsensitive matching.

Figure 23-18

577

Chapter 23

How It Works

The example uses the preg_grep() method twice: — first to match case sensitively (the default), and second to match case insensitively.

The array that is matched is $myArray, which is assigned an array of values shown here:

$myArray = array(“Hello”, “Help”, “helper”, “shell”, “satchel”, “Camera”);

First, the case-sensitive matching is carried out. The $myMatchesSensitive variable is assigned the array returned from the preg_grep() function, using the literal pattern “/Hel/” as its first argument and $myArray as its second argument:

$myMatchesSensitive = preg_grep(“/Hel/”, $myArray);

A message about case-sensitive matching is displayed:

echo “<p>Matching case sensitively:</p>”;

Then the value of the $myMatchesSensitive variable is used as a test for an if statement. If the $myMatchesSensitive variable contains a nonempty array, the statement in the if statement is executed:

if ($myMatchesSensitive)

The print_r() function is used to display the key and values of the array elements in $myArray. The print_r() function prints human-readable information about a function.

Only two elements containing matches, Hello and Help, are found when matching is case sensitive:

{

print_r (array_values($myMatchesSensitive));

}

The process is repeated for case-insensitive matching. The $myMatchesInsensitive variable is assigned the array returned from the preg_grep() function. Notice in the first argument that the i matching modifier is used to specify case-insensitive matching:

$myMatchesInsensitive = preg_grep(“/Hel/i”, $myArray);

A message about case-insensitive matching is displayed:

echo “<br /><p>Matching case insensitively:</p>”;

Then the if statement tests if $myMatchesInsensitive is empty. If not, the print_r() function is used to output information about the case-insensitive matches.

When using case-insensitive matching, three additional elements containing matches are found: helper, shell, and satchel.

if ($myMatchesInsensitive)

{

print_r (array_values($myMatchesInsensitive));

}

578

PHP and Regular Expressions

Using the preg_quote() Function

The preg_quote() function is used to escape strings produced at runtime that may contain values that would be misinterpreted without escaping. You could use preg_quote() to match a period character, for example. In the output string, the period character would be escaped, being written as \..

Using the preg_replace() Function

The preg_replace() function attempts to match a regular expression as many times as possible in a test string. Each substring that is a match is replaced by specified replacement text.

The preg_replace() function takes three or more arguments. The first argument is a regular expression pattern. The second is the replacement text. The third is the test string. The optional fourth argument is an int value that indicates a maximum number of times that replacement should take place.

The e matching modifier causes back references in the replacement text to be interpreted as PHP code and uses the result to replace the test string.

Try It Out

Using the preg_replace() Function

The following illustrates how you can use the preg_replace() function to replace the literal text Star with the literal text Moon.

1.Type the following code in a text editor:

<html>

<head>

<title>A preg_replace() Demo</title> </head>

<body>

<?php

$myString = “Star Training Company.”;

$newString = preg_replace(“/Star/”, “Moon”, $myString); echo “<p>The original string was: ‘$myString’.</p>”;

echo “<p>After replacement the string is: ‘$newString’.</p.>”; ?>

</body>

</html>

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

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

Figure 23-19

579