Trong ví dụ này, nhiều PHP 5 tính năng đang được sử dụng để xây dựng một lớp RegExp mạnh mẽ mà bạn có thể sử dụng trong mã của bạn. Vào cuối của ví dụ, mã chứng minh làm thế nào để sử dụng lớp mới. Các nhà xây dựng __construct là được sử dụng với các biểu hiện thường xuyên như là một tham số để constructor. | 386 9-20 CREATING YOUR OWN REGEXP CLASS - str The string in which to make the replacement function replace replaceStr str result preg_replace this- pattern replaceStr str return result re new RegExp Hello echo re . n echo 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 echo Didn t find match n res re- replace Goodbye Goodbye world echo res . n How It Works In this example many new PHP 5 features are being used to build a powerful RegExp class that you can use in your code. At the end of the example code demonstrates how to use the new class. Theconstruct constructor is used with the regular expression as an argument to the constructor. When a new RegExp object is created the pattern is kept inside the object to use in its future matches and replacements. The class declaration and constructor are as follows class RegExp public pattern Constructor Creates a new instance of the RegExp object with the pattern given. function construct pattern this- pattern pattern 9-20 CREATING YOUR OWN REGEXP CLASS 387 To create an instance of the RegExp class just create it using new as shown here and in the test code at the bottom of the example re new RegExp Hello In the previous example Hello will be stored in the pattern variable in the class. The_toString method is declared in this class to print the regular expression in the pattern variable so using echo to print the object will print the pattern only echo re This is the result Hello Now that the object has been created and is storing a regular expression internally the isMatch function shown next will make it easy to see if there is a match found inside a string function isMatch str result preg_match this- pattern str return result As you can see this class uses the PCRE function preg_match to look at the string to see if there is a match with this- pattern used as the regular expression. This is why the example regular .