PHP Regular Expressions

Description

Regular expressions provide us with a special syntax for searching for patterns of text within strings.

Syntax

Regular expressions are created by a forward slash /, followed by a sequence of symbols, then another slash and, optionally, a letter.

For example, this simple regular expression searches for the word "world" anywhere within the target string:

/world/

Example

The following table shows a list of very basic regular expressions and strings, and whether or not a match is made.

Function callResult
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:


<?PHP/*w  ww. ja  v a2s  .c  o  m*/
if (preg_match("/php/i", "PHP")) {
    print "Got match!\n";
}
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Development »




Environment
Error
Hash
Include
Locale
Math
Network
Output
Reflection
PHP Regular Expressions