PHP Regular Expressions
Complete Guide in Hindi
PHP Regex की पूरी जानकारी — Pattern syntax, preg_match, preg_replace, preg_split, preg_grep। Email, mobile, URL, password validation। Real examples के साथ।
📋 इस Article में क्या-क्या है
- Regex क्या है?
- Pattern Syntax — Characters
- Quantifiers
- Anchors & Groups
- Flags (Modifiers)
- preg_match()
- preg_match_all()
- preg_replace()
- preg_split() & preg_grep()
- Common Patterns — Real World
Regular Expression (Regex) — एक pattern जो strings में search, validate, और replace करता है। Email check करना, phone number validate करना, HTML tags हटाना — सब regex से।
/^[a-z]+@[a-z]+\.[a-z]{2,}$/i
// Delimiter: / ... /
// Anchor: ^ = start, $ = end
// Char class: [a-z] = a से z कोई भी
// Quantifier: + = एक या ज़्यादा, {2,} = 2+
// Flag: i = case insensitive
| Pattern | मतलब | Example Match |
|---|---|---|
| . | कोई भी एक character (newline छोड़) | a, b, 1, @ |
| \d | Digit [0-9] | 0, 5, 9 |
| \D | Non-digit | a, !, space |
| \w | Word char [a-zA-Z0-9_] | a, Z, 5, _ |
| \W | Non-word char | @, !, space |
| \s | Whitespace (space, tab, newline) | space, \t |
| \S | Non-whitespace | a, 1, @ |
| [abc] | a, b, या c में से एक | a, b, c |
| [^abc] | a, b, c को छोड़कर कोई भी | d, e, 1 |
| [a-z] | a से z कोई भी | a, m, z |
| [0-9] | 0 से 9 कोई भी | 0, 5, 9 |
| [a-zA-Z] | कोई भी letter | a, Z, m |
| \. | Literal dot (escape) | . |
| a|b | a या b (alternation) | cat, bat |
// \d — digits
preg_match("/\d+/", "Order 12345", $m);
echo $m[0]; // 12345
// \w — word characters
preg_match("/\w+/", "Hello World", $m);
echo $m[0]; // Hello
// [aeiou] — vowels
preg_match_all("/[aeiou]/i", "Hello World", $m);
print_r($m[0]); // [e, o, o]
// [^0-9] — non-digits
echo preg_replace("/[^0-9]/", "", "Phone: 9876543210");
// 9876543210
?>
| Quantifier | मतलब | Example |
|---|---|---|
| * | 0 या ज़्यादा बार | ab* → a, ab, abb, abbb |
| + | 1 या ज़्यादा बार | ab+ → ab, abb (not a) |
| ? | 0 या 1 बार (optional) | colou?r → color, colour |
| {n} | exactly n बार | \d{4} → 2025 |
| {n,} | n या ज़्यादा बार | \d{2,} → 12, 123, 1234 |
| {n,m} | n से m बार | \d{2,4} → 12, 123, 1234 |
| *? | Lazy — minimum match | <.+?> → <b> not <b>text</b> |
| +? | Lazy one or more | Stops at first match |
$html = "<b>Bold</b> and <i>Italic</i>";
// Greedy — maximum match (default)
preg_match("'<.+>'", $html, $m);
echo $m[0]; // <b>Bold</b> and <i>Italic</i> — all!
// Lazy — minimum match (? add करो)
preg_match("'<.+?>'", $html, $m);
echo $m[0]; // <b> — first tag only
// {n} exact count
preg_match("/\d{6}/", "PIN: 110001", $m);
echo $m[0]; // 110001
?>
| Symbol | मतलब | Example |
|---|---|---|
| ^ | String का start | ^Hello → "Hello World" ✅ |
| $ | String का end | World$ → "Hello World" ✅ |
| \b | Word boundary | \bcat\b → "cat" not "catch" |
| (abc) | Capture group | (ab)+ → ab, abab |
| (?:abc) | Non-capture group | Group but don't capture |
| (?P<name>) | Named capture group | (?P<year>\d{4}) |
| \1 \2 | Backreference | (abc)\1 → abcabc |
| (?=abc) | Lookahead | foo(?=bar) → foobar |
| (?!abc) | Negative lookahead | foo(?!bar) → fooXXX |
// ^ $ — String boundaries
var_dump(preg_match("/^Hello/", "Hello World")); // 1 (true)
var_dump(preg_match("/^World/", "Hello World")); // 0 (false)
// Capture groups — () — $matches में save
preg_match("/(\d{4})-(\d{2})-(\d{2})/", "2025-05-15", $m);
echo $m[0]; // 2025-05-15 (full match)
echo $m[1]; // 2025 (group 1)
echo $m[2]; // 05 (group 2)
echo $m[3]; // 15 (group 3)
// Named groups — (?P<name>pattern)
preg_match("/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/", "2025-05-15", $m);
echo $m["year"]; // 2025
echo $m["month"]; // 05
echo $m["day"]; // 15
// \b word boundary
preg_match_all("/\bPHP\b/i", "PHP is great. PHPStorm too.", $m);
echo count($m[0]); // 1 — PHP only, not PHPStorm
?>
| Flag | मतलब | Example |
|---|---|---|
| i | Case-insensitive | /hello/i → Hello, HELLO, hello |
| m | Multiline — ^ $ हर line पर | /^\d/m → each line start |
| s | Dotall — . newlines भी match करे | /a.b/s → "a\nb" |
| g | Global (PHP में preg_match_all) | All matches find |
| x | Extended — whitespace ignore, comments | Readable patterns |
| u | Unicode — UTF-8 support | Hindi/Chinese chars |
// i — case insensitive
preg_match("/php/i", "I love PHP"); // 1 — PHP, php, Php सब match
// m — multiline
$text = "line1\nline2\nline3";
preg_match_all("/^line/m", $text, $m);
echo count($m[0]); // 3 — हर line का start
// s — dotall (. newline भी)
preg_match("/start.+end/s", "start\nmiddle\nend"); // 1
// u — unicode (Hindi support)
preg_match("/^\p{L}+$/u", "राहुल"); // 1 — Unicode letters
// x — extended (readable pattern)
$emailPattern = "/ ^ # Start [a-z0-9._-]+ # Local part @ # @ symbol [a-z0-9.-]+ # Domain \. # Dot [a-z]{2,} # TLD $ # End /ix";
?>
// Simple check — match है?
if (preg_match("/^\d{10}$/", "9876543210")) {
echo "✅ Valid 10-digit number";
}
// $matches — captured groups
if (preg_match("/^(\w+)\s(\w+)$/", "Rahul Kumar", $matches)) {
echo $matches[0]; // "Rahul Kumar" (full)
echo $matches[1]; // "Rahul" (first name)
echo $matches[2]; // "Kumar" (last name)
}
// Date extract
$log = "Error at 2025-05-15 14:30:00: Connection failed";
if (preg_match("/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/", $log, $m)) {
echo "Date: " . $m[1]; // 2025-05-15
echo "Time: " . $m[2]; // 14:30:00
}
?>
// सब email addresses extract करो
$text = "Contact us at rahul@gmail.com or support@hnp.in for help.";
$count = preg_match_all("/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/i", $text, $matches);
echo "Found $count emails:\n";
print_r($matches[0]); // [rahul@gmail.com, support@hnp.in]
// All prices extract
$prices = "Items: ₹450, ₹799, ₹299, ₹1,299";
preg_match_all("/₹([\d,]+)/", $prices, $m);
print_r($m[1]); // [450, 799, 299, 1,299]
// HTML links extract
$html = '<a href="https://php.net">PHP</a> <a href="https://hnp.in">HNP</a>';
preg_match_all('/href="([^"]+)"/', $html, $m);
print_r($m[1]); // [https://php.net, https://hnp.in]
// Hashtags extract
$post = "Learning #PHP and #MySQL! #HindiNotes";
preg_match_all("/\#(\w+)/", $post, $m);
print_r($m[1]); // [PHP, MySQL, HindiNotes]
?>
// Simple replace
echo preg_replace("/PHP/i", "Python", "I love PHP!");
// I love Python!
// Multiple spaces → single
echo preg_replace("/\s+/", " ", "Hello World PHP");
// Hello World PHP
// HTML tags remove
echo preg_replace("'<[^>]+>'", "", "<b>Bold</b> text");
// Bold text
// Backreferences — $1, $2
// Date format change: 2025-05-15 → 15/05/2025
echo preg_replace("/(\d{4})-(\d{2})-(\d{2})/", "$3/$2/$1", "2025-05-15");
// 15/05/2025
// Mask phone number: 9876543210 → 98XXXXXX10
echo preg_replace("/(\d{2})\d{6}(\d{2})/", "$1XXXXXX$2", "9876543210");
// 98XXXXXX10
// preg_replace_callback — complex logic
$text = "price: 100, 200, 300";
echo preg_replace_callback("/\d+/", fn($m) => $m[0] * 1.18, $text);
// price: 118, 236, 354 (18% GST add)
?>
// preg_split — pattern से split (explode का powerful version)
// Multiple delimiters — comma, semicolon, pipe
$str = "PHP, MySQL; Laravel | React";
$parts = preg_split("/[,;|]\s*/", $str);
print_r($parts); // [PHP, MySQL, Laravel, React]
// Whitespace split
$words = preg_split("/\s+/", "Hello World PHP");
print_r($words); // [Hello, World, PHP]
// CamelCase को words में split
$camel = "camelCaseVariableName";
$words = preg_split("/(?=[A-Z])/", $camel);
print_r($words); // [camel, Case, Variable, Name]
// preg_grep — array filter with regex
$emails = ["r@gmail.com", "invalid", "p@yahoo.in", "notanemail"];
$valid = preg_grep("/^[a-z0-9.]+@[a-z0-9]+\.[a-z]{2,}$/i", $emails);
print_r($valid); // [r@gmail.com, p@yahoo.in]
// preg_grep — inverse (match नहीं करने वाले)
$invalid = preg_grep("/^[a-z0-9.]+@[a-z0-9]+\.[a-z]{2,}$/i", $emails, PREG_GREP_INVERT);
print_r($invalid); // [invalid, notanemail]
?>
$emailPattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
var_dump(preg_match($emailPattern, "rahul@gmail.com")); // 1
// Indian Mobile — 6-9 से शुरू, 10 digits
$mobilePattern = "/^[6-9]\d{9}$/";
var_dump(preg_match($mobilePattern, "9876543210")); // 1
// Indian PIN code — 6 digits, 1-9 से शुरू
$pinPattern = "/^[1-9]\d{5}$/";
var_dump(preg_match($pinPattern, "110001")); // 1
// URL
$urlPattern = "/^https?:\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,}(\/.*)?$/i";
var_dump(preg_match($urlPattern, "https://hindinotespoint.in")); // 1
// Password — 8+, uppercase, lowercase, digit
$passPattern = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/";
var_dump(preg_match($passPattern, "MyPass123")); // 1
var_dump(preg_match($passPattern, "weakpass")); // 0
// GST Number — 15 chars: 2digit state + 10 PAN + 1Z + 2alphanumeric
$gstPattern = "/^\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}Z[A-Z\d]{1}$/";
var_dump(preg_match($gstPattern, "29ABCDE1234F1ZS")); // 1
// Aadhaar — 12 digits (not starting with 0 or 1)
$aadhaarPattern = "/^[2-9]\d{11}$/";
var_dump(preg_match($aadhaarPattern, "234567891234")); // 1
// Slug — URL-safe lowercase
$slugPattern = "/^[a-z0-9]+(?:-[a-z0-9]+)*$/";
var_dump(preg_match($slugPattern, "php-tutorial-hindi")); // 1
// Slug बनाना from title
function makeSlug(string $title): string {
$slug = strtolower(trim($title));
$slug = preg_replace("/[^a-z0-9\s-]/", "", $slug); // Non-alphanumeric remove
$slug = preg_replace("/\s+/", "-", $slug); // Spaces → dash
return preg_replace("/--+/", "-", $slug); // Multiple dashes → one
}
echo makeSlug("PHP Tutorial for Beginners!");
// php-tutorial-for-beginners
?>
| Function | काम | Returns | Use Case |
|---|---|---|---|
| preg_match() | Pattern match check | 0 or 1 | Validation |
| preg_match_all() | All matches find | int (count) | Extract all emails/links |
| preg_replace() | Pattern replace | string | Format change, clean |
| preg_replace_callback() | Custom replacement logic | string | Complex transforms |
| preg_split() | Pattern से split | array | Multiple delimiters |
| preg_grep() | Array filter by pattern | array | Filter valid emails |
| preg_quote() | Special chars escape | string | User input in pattern |
// User input को pattern में safe use करना
$search = "C++ (language)"; // Special chars!
$escaped = preg_quote($search, "/"); // C\+\+ \(language\)
$pattern = "/" . $escaped . "/i";
preg_match($pattern, "I love C++ (language)"); // ✅ safe
?>
Regular Expressions PHP का powerful feature है। एक बार सीखने के बाद validation, text processing, और data extraction बहुत आसान हो जाती है।
preg_match — validate (0/1)। preg_match_all — extract all। preg_replace — transform।
^ $ — String boundaries। Validation में हमेशा use करो।
() — Capture groups। $matches[1] से access। Named: (?P<name>)।
Greedy vs Lazy — .+ greedy (max), .+? lazy (min)। HTML parse में lazy use करो।
preg_quote() — User input को pattern में use करने से पहले escape करो।
filter_var(FILTER_VALIDATE_EMAIL) — Email के लिए regex से बेहतर।