π PHP Regular Expressions (RegEx) – Pattern Matching in PHP
Ever wanted to find a specific word in a sentence, validate an email, or replace text automatically? Well, that’s what Regular Expressions (RegEx) are for! π
PHP provides powerful functions to work with RegEx, such as preg_match()
, preg_replace()
, and preg_match_all()
. Letβs break it down with fun examples! π
π What is a Regular Expression?
A Regular Expression (RegEx) is a pattern that helps match, search, and replace text. Think of it as a **text detective** π΅οΈββοΈ that finds exactly what you need in a string.
π Commonly Used RegEx Functions in PHP
preg_match()
– Finds the first match in a string.preg_match_all()
– Finds all matches in a string.preg_replace()
– Replaces matched text with something else.
π Example 1: Checking if a String Contains a Word
Let’s check if a string contains the word “PHP”:
<?php $text = "I love PHP and coding!"; $pattern = "/PHP/"; if (preg_match($pattern, $text)) { echo "Match found!"; } else { echo "No match found!"; } ?>
π Output: “Match found!”
π Example 2: Finding All Numbers in a String
Let’s extract all numbers from a string using preg_match_all()
.
<?php $text = "I have 2 apples and 5 bananas."; $pattern = "/\d+/"; // \d+ matches one or more digits preg_match_all($pattern, $text, $matches); print_r($matches[0]); // Output: Array ( [0] => 2 [1] => 5 ) ?>
π― This extracts: 2
and 5
from the string.
π Example 3: Replacing Text with preg_replace()
Want to replace “apples” with “oranges”? Use preg_replace()
! πβ‘οΈπ
<?php $text = "I love apples!"; $pattern = "/apples/"; $replacement = "oranges"; $new_text = preg_replace($pattern, $replacement, $text); echo $new_text; // Output: I love oranges! ?>
π Output: “I love oranges!”
π Useful Regular Expressions Patterns
Pattern | Description | Example Match |
---|---|---|
/\d+/ |
Finds numbers | “I have 2 apples.” |
/[a-z]+/ |
Finds lowercase words | “I like coding.” |
/[A-Z]+/ |
Finds uppercase words | “HELLO WORLD!” |
/\w+/ |
Finds words (letters & numbers) | “My username is user123.” |
/\s/ |
Finds whitespace | “Hello World” |
π― Summary
- β RegEx helps find, validate, and replace text efficiently.
- β
preg_match()
finds the first match. - β
preg_match_all()
finds all matches. - β
preg_replace()
replaces matched text.
π Next Steps
Try experimenting with different patterns to master PHP RegEx! π