Приглашаем посетить
Есенин (sergeiesenin.lit-info.ru)

Section 15.1.  Basic Regexps with preg_match( ) and preg_match_all( )

Previous
Table of Contents
Next

15.1. Basic Regexps with preg_match( ) and preg_match_all( )

The basic regexp function is preg_match( ) and it takes two parameters: the pattern to match and the string to match it against. It will apply the regular expression in parameter one to the string in parameter two and see whether it finds a matchif it does, it will return 1; otherwise, 0. The reason it returns 1 is because regular expressions return the number of matches found, but preg_match( ), for speed reasons, returns as soon as it finds the first matchthis means it is very quick to check whether a pattern exists in a string. An alternative function, preg_match_all( ), does not exit after the first match; we will get to that later in this chapter.

Regular expressions are formed by starting with a forward slash /, followed by a sequence of special symbols and words to match, then another slash and, optionally, a string of letters that affect the expression. Table 15-1 shows a list of very basic regular expressions and strings, and whether or not a match is made.

Table 15-1. preg_match( ) calls and what they match

Function call

Result

preg_match("/php/", "php")

True

preg_match("php/", "php")

Error; you need a slash at the start

preg_match("/php/", "PHP")

False; regexps are case-sensitive

preg_match("/php/i", "PHP")

True; /i means "case-insensitive"

preg_match("/Foo/i", "FOO")

True


The i modifier makes regexps case-insensitive.

The preg_match( ) returns true if there is a match, so you can use it like this:

    if (preg_match("/php/i", "PHP")) {
            print "Got match!\n";
    }


Previous
Table of Contents
Next