Regular expression also called RegEx, is a pattern of characters used to find, replace, split text from a given string and also validates input. Regular expression is case sensitive. It allows to works with single character to a complicated string pattern easily.

PHP Regular expression functions

preg_match()finds only first match of searched string in given string. If found returns true.
preg_match_all()finds all matches in a given string.
preg_replace()It finds the searched pattern string and replace it with given string and returns new string.
preg_split()It searches the given pattern in a string and split the string and returns array.
preg_quote()It adds backslash at the beginning and where the match found in a given string.

Regular Expression Modifiers

icase sensitive search and replace
mmultiline search and replace (By default single line)
uMatches UTF-8 characters

Regular Expression Patterns

[abc][Hello]Find string or characters inside brackets
[^abc][^Hello Worldz]Do not find string or characters inside brackets
[a-z][l-o] [^Hello Worldz]Finds all character From l to O in a given string and replace it.
[A-z][l-o] [^Hello Worldz]Finds all Uppercase and lowercase character From l to O in a given string and replace it.
[A-Z][H-W] [^Hello Worldz]Finds all Uppercase character From H to W in a given string and replace it.
[123]Finds digit(s) in given string
[0-5]Find digit from 0 to 5 in given string.
[Hello|Hi]Either of text

Metacharacters

|any of given characters or string
.any single character
^start of the string
$find match at the end of string
()to group expression
[]given characters inside bracket
[^]not any given characters inside bracket
\dfind digits from 0-9
\Ddo not find digits
\wfinds any digit or character
\Wdo not any digit or character
\bFind match at the beginning of sentence
\sFinds whitespace character, newline or tab
\SFinds non-whitespace character, newline or tab
\uxxxx

Quantifiers

r+Matches any string if contain at least one r
r*Matches any string if contain one or more r
r?Matches any string if contain one or zero r
r{a}matches any string with a sequence of A r’s.
r{a,b}Matches any string which contains sequence of A to B r’s
r{a,}Matches any string which contains sequence of at least A r’s
r$Matches any string which contains r at the end.
^rMatches any string which contain r at the start.