Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

PHP 5 Recipes A Problem-Solution Approach 2005 phần 7 doc
Nội dung xem thử
Mô tả chi tiết
The modified class is as follows, with the additions in bold:
<?php
class RegExp {
const POSIX = 'POSIX';
const PCRE = 'PCRE';
public $pattern;
public $mode;
// Constructor
// Creates a new instance of the RegExp object
// with the pattern given.
function __construct($pattern, $mode) {
$this->pattern = $pattern;
if (! $mode) {
// Defaults to PCRE if there is no mode defined
$this->mode = self::PCRE;
} else {
// In a real implementation, this $mode should be validated—check
// it against the PRCE and POSIX constants
$this->mode = $mode;
}
}
// prints the string representation of the RegExp object,
// which in this case is the pattern
function __toString() {
return $this->pattern;
}
// isMatch($str)
// Returns the number of matches found, so is 0 if
// no match is present.
function isMatch($str) {
if (strcmp($this->mode, self::PCRE)==0) {
$result = preg_match($this->pattern, $str);
} else {
$result = ereg($this->pattern, $str);
}
return $result;
}
// getMatches($str)
// Returns an array of matches found in the string $str
function getMatches($str) {
388 9-20 ■ CREATING YOUR OWN REGEXP CLASS
5092_Ch09_FINAL 8/26/05 9:54 AM Page 388
if (strcmp($this->mode, self::PCRE)==0) {
preg_match_all($this->pattern, $str, $matches);
} else {
ereg($this->pattern, $str, $matches);
}
return $matches;
}
// replace($replaceStr, $str)
// Makes a replacement in a string
// -$replaceStr: The string to use as a replacement
// for the pattern.
// -$str: The string in which to make the replacement
function replace($replaceStr, $str) {
if (strcmp($this->mode, self::PCRE)==0) {
$result = preg_replace($this->pattern, $replaceStr, $str);
} else {
$result = ereg_replace($this->pattern, $replaceStr, $str);
}
return $result;
}
}
?>
The strcmp function compares the mode against the PCRE constants because it is a value
that needs exact matching, and strcmp is a more efficient method of doing this particular
comparison.
The following code uses this new and improved class that supports both PCRE and POSIX
regular expressions:
$re = new RegExp('/Hello/', RegExp::PCRE);
$re2 = new RegExp('Hello', RegExp::POSIX);
print "Using PCRE: \n\n";
print "Pattern: " . $re->pattern . "\n";
if ($re->isMatch('Goodbye world!')) {
echo "Found match!\n";
} else {
echo "Didn't find match!\n";
}
if ($re->isMatch('Hello world!')) {
echo "Found match!\n";
} else {
9-20 ■ CREATING YOUR OWN REGEXP CLASS 389
5092_Ch09_FINAL 8/26/05 9:54 AM Page 389
echo "Didn't find match!\n";
}
$res = $re->replace('Goodbye', 'Hello world!');
echo $res . "\n";
print "\n\nUsing POSIX: \n\n";
print "Pattern: " . $re2->pattern . "\n";
if ($re2->isMatch('Goodbye world!')) {
echo "Found match!\n";
} else {
echo "Didn't find match!\n";
}
if ($re2->isMatch('Hello world!')) {
echo "Found match!\n";
} else {
echo "Didn't find match!\n";
}
$re2s = $re2->replace('Goodbye', 'Hello world!');
echo $re2s . "\n";
When the code here is executed, the output will look like this:
Using PCRE:
Pattern: /Hello/
Didn't find match!
Found match!
Goodbye world!
Using POSIX:
Pattern: Hello
Didn't find match!
Found match!
Goodbye world!
Notice that the patterns are a little different between the two objects. This is because the
PCRE version of the regular expression requires delimiters at the beginning and the end of the
expression—in this case, the / character.
390 9-20 ■ CREATING YOUR OWN REGEXP CLASS
5092_Ch09_FINAL 8/26/05 9:54 AM Page 390
Summary
PHP supports two implementations of regular expressions—POSIX and PCRE. PCREs support
more character classes and special features such as nongreedy matching and look-arounds.
Regular expressions allow you to do much more than simple searching and replacing
within strings. Using regular expressions in PHP, you can find strings according to specific
rules, validate user input, process files such as CSV and tab-delimited files, and make complicated replacements in text. Combined with the other capabilities in PHP, the possibilities are
nearly endless.
For more about using regular expressions, see Regular Expression Recipes: A ProblemSolution Approach (Apress, 2005) and Regular Expression Recipes for Windows Developers:
A Problem-Solution Approach (Apress, 2005).
Looking Ahead
In the next chapter, Frank M. Kromann explores the world of variables in PHP, showing some
advanced variable functions that you will find invaluable in your everyday programming.
9-20 ■ CREATING YOUR OWN REGEXP CLASS 391
5092_Ch09_FINAL 8/26/05 9:54 AM Page 391
5092_Ch09_FINAL 8/26/05 9:54 AM Page 392
Working with Variables
Variables are an important part of any programming language, and that goes for PHP too.
Variables are blocks of memory associated with a name and a data type, and variables contain
data to be used in calculations, program flow, presentation, and so on.
PHP is a loosely typed language where variables can be used without declarations and
where they can change type from line to line, in some cases without losing the content. This
makes programming much easier than in more strictly typed languages, but it can also make
it more difficult to debug the code.
All variable names in PHP start with a dollar ($) sign. This makes it easy for the scripting
engine, as well as the reader, to identify variables anywhere in the code, including when they
are embedded in strings. Also, using the $ sign allows the developer to use variable names
that would otherwise be reserved by the engine for function names and language constructs.
This means writing code where function names are used as variable names, such as
$strlen = strlen("This is a test");, is allowed.
The first character after the $ sign in a variable name must be a letter or an underscore
(_). The remaining characters can be letters, numbers, and underscores, and there is no limit
on the length of a variable name (but it makes sense to keep them short and meaningful to
ensure the readability of the code). Using short variable names means less typing when writing the code, and using longer names means more descriptive names. Valid letters are any of
the characters a–z, the characters A–Z, and any ASCII character from 127 to 255. This makes it
possible to use international characters when naming variables. $LøbeNummer is a valid variable name but most likely readable only to Danish developers. We prefer to keep variable and
function names as well as all comments in English like all the language constructs and built-in
functions.
It is also important to note that although function names are case-insensitive in PHP, this
is not the case for variables. $MyVar and $myvar are two different variables in PHP, and this is
often the cause of scripting warnings. If PHP is configured to hide errors and warnings, it will
be difficult to catch programming errors caused by the misspelling of variables as well as other
mistakes. It is recommended to configure PHP (on the development system) to display all
errors and warnings; you can do this by defining these two values in php.ini:
error_reporting = E_ALL
display_errors = On
393
CHAPTER 10
■ ■ ■
5092_Ch10_FINAL 8/26/05 9:56 AM Page 393