PHP Regular Expressions

πŸ” 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!";
}
?>

Try It Now

πŸ” 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 )
?>

Try It Now

🎯 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!
?>

Try It Now

πŸ” 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! πŸš€