Regular expressions (RegEx) are a powerful way to match and manipulate text. PHP provides functions to work with regular expressions via the PCRE (Perl Compatible Regular Expressions) library.
1. Basic Syntax
A regular expression is a pattern that describes a set of strings. They can be used for searching, extracting, and modifying textual data.
In PHP, regex patterns are typically delimited with slashes (`/`). For example:
$pattern = '/abc/';
This pattern matches the string "abc". 2. Basic Functions
3. Basic Patterns
Examples:
if (preg_match('/\d/', 'abc123')) { // true because there's a digit
echo "There's a digit!";
}
echo preg_replace('/\d/', '*', 'abc123'); // Outputs: abc***
$words = preg_split('/\s/', 'Hello World'); // Splits on whitespace: ['Hello', 'World']
4. Quantifiers
Examples:
// Match "a" followed by one or more "b"s
if (preg_match('/ab+/', 'abb')) {
echo "Match!";
}
// Match "a" followed by 2 to 4 "b"s
if (preg_match('/ab{2,4}/', 'abbb')) {
echo "Match!";
}
5. Grouping and Capturing Use parentheses `()` to group part of a pattern. Example:
if (preg_match('/(ab)+/', 'abab')) {
echo "Repeated ab!";
}
6. Character Sets and Classes Use square brackets `[]` to match any one of the characters inside. Examples:
if (preg_match('/[aeiou]/', 'apple')) {
echo "Vowel found!";
}
if (preg_match('/[^aeiou]/', 'apple')) {
echo "Non-vowel found!";
}
7. Modifiers
Example:
if (preg_match('/apple/i', 'APPLE')) {
echo "Case-insensitive match!";
}
8. Anchors
Example:
if (preg_match('/^apple/', 'apple pie')) {
echo "String starts with apple!";
}
9. Escape Sequences If you want to match characters that have special meaning in regex, like `.`, `*`, `?`, and so on, you should escape them with a backslash `\`. Example:
if (preg_match('/\.com/', 'example.com')) {
echo ".com found!";
}
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here