Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Last active September 3, 2021 07:35
Show Gist options
  • Save junaidtk/48aed06c38c08fd374c31c6449f772f9 to your computer and use it in GitHub Desktop.
Save junaidtk/48aed06c38c08fd374c31c6449f772f9 to your computer and use it in GitHub Desktop.
Regex or Regular Expression.
Regular expression are patterns/combination of charactor used to match character, group of character or any combinations in a string.
$regular_expression = '';
Regular expression is pattern which is enclosed between slashes.
So our reqular expression become,
$regular_expression = '//';
^ This will match the begining of a line.
$ will indicate the end of a line.
So $regular_expression become,
$regular_expression = '/^abc$/'; // match for string abc (start with abc, end with abc).
. : Match any single charactor except new line
[abc] : match for a,b or c.
[a-z] : match all lower case letter.
[^A-Z] : Macth all non capital letters.
[a-z]+ : One or more lower case letters.
[] : range of charactor.
() : group of expression.
| : Logical OR operation.
b+ : Match any string with b one atleast (one or more).
b* : Match any string constinaing zero or more b.
b? : Match any string zero or one b.
b{n} : denotes exactly n times of preceding character (b).
b{n, } : at least n times.
b.b : match a string contain b followed by any charactor then followed by b.
hello(.*)haii : match string enclosed between hello and haiii.
^.{2}$ : Match exactly 2 charactor.
\s : Match any space charactor.
\S : Match any non white space charactor.
\d : Match any decimal number(0-9).
\D : Match any Non digit charactor.
\w : Match word charactor. Same as [a-zA-Z_0-9].
\W : Match any non word charactor.
\ : It indicate the escape charactor. So if we put this before any reserved charactors like (+, *,.,/,{,},[,] etc...),
Then it will take the reseved charactor as literaly same charactor.
Regular expression functions in php:
preg_match(); ==== Search for a string, and return true or flase.
preg_match_all(); === Search for a pattern globally, return matched.
preg_replace(); === Replace a specific pattern.
preg_split(); === Split the string using regex.
preg_grep(); === Search all elemnt of input array and Return element of matched array.
Regular expression can be test in the below website to check the expression is correct or not.
https://regexr.com/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment