Regular expressions in PHP

Regular expressions is a special text string for describing a search pattern. Regular expressions are used to

1) Search a string inside a string
2) Replace strings
3) Split strings
4) Data Validation (email address, IP address)

The PHP function preg_match() searches string for pattern and returns TRUE or FALSE. Other PHP functions for Regular expressions are preg_split(), preg_replace(), preg_match_all(), preg_grep(), preg_ quote().

Here is quick look at the 3 commonly used PHP regular expression functions.

1) preg_match()

Syntax for the PHP function preg_match() is as below:

preg_match(‘/regex/’, $string);

Example code

$var = “hello world”;
preg_match(‘/hello/’, $var); // This will return TRUE

2) preg_split()

Syntax for the PHP function preg_split() is as below:

preg_split(“/ /”, $string);

Example code

$var = “hello world”;
preg_split(“/ /”, $var); // Array([0]=>hello[1]=>world)

3) preg_replace()

Syntax for the PHP function preg_replace() is as below:

preg_replace(“/regex/”, $replace, $string);

Example code

$var = “hello world”;
preg_replace(“/world/”, ‘earth’, $var); // hello earth

Any forward slash in the regular expression must be escaped with a backward splash (\) if you are using forward slash (/) as the delimiter. However you may use any non-alphanumeric character as regex delimiters.

BRACKETS

Brackets([]) are used to find a range of characters.

[0-9] – any decimal from 0 to 9
[a-z] – any character from lowercase a through lowercase z
[A-Z] – any character from uppercase a through uppercase z

Meta characters

Metacharacters are used to perform more complex pattern matches such as validity of an email address. Here is a list of commonly used metacharacters.

Character Description

. a single character
^ beginning of or string
$ pattern at the end of the string
\ to escape meta characters
+ Requires preceding character(s) appear at least once

.entry-meta
#post-

Leave a Reply