0
0
PhpHow-ToBeginner · 3 min read

How to Use Regex in PHP: Syntax and Examples

In PHP, you use regex with functions like preg_match() to check if a pattern matches a string, and preg_replace() to replace parts of a string using a pattern. Regex patterns are enclosed in delimiters like /pattern/ and can include modifiers for case or global matching.
📐

Syntax

PHP uses functions starting with preg_ to work with regex. The pattern is enclosed in delimiters, usually slashes /pattern/. You can add modifiers like i for case-insensitive matching.

  • preg_match(pattern, subject): Checks if pattern matches subject.
  • preg_replace(pattern, replacement, subject): Replaces matches with replacement.
php
<?php
$pattern = '/hello/i'; // 'i' means case-insensitive
$subject = 'Hello World';
if (preg_match($pattern, $subject)) {
    echo "Match found!";
} else {
    echo "No match.";
}
?>
Output
Match found!
💻

Example

This example shows how to find if a string contains the word 'cat' ignoring case, and how to replace 'dog' with 'cat' in a sentence.

php
<?php
// Check if 'cat' is in the string (case-insensitive)
$pattern = '/cat/i';
$text = 'The Cat sat on the mat.';
if (preg_match($pattern, $text)) {
    echo "Found 'cat' in the text.\n";
} else {
    echo "'cat' not found.\n";
}

// Replace 'dog' with 'cat'
$sentence = 'The dog chased the dog.';
$replaced = preg_replace('/dog/i', 'cat', $sentence);
echo $replaced;
?>
Output
Found 'cat' in the text. The cat chased the cat.
⚠️

Common Pitfalls

Common mistakes include forgetting delimiters around the pattern, not escaping special characters, and misunderstanding modifiers.

  • Always use delimiters like /pattern/.
  • Escape special characters like ., ?, * if you want to match them literally.
  • Use i modifier for case-insensitive matching.

Example of wrong and right usage:

php
<?php
// Wrong: missing delimiters
// $pattern = 'hello'; // This will cause an error

// Right: with delimiters
$pattern = '/hello/';

// Wrong: unescaped dot matches any character
$patternWrong = '/file.name/'; // matches fileXname

// Right: escaped dot matches literal dot
$patternRight = '/file\.name/';
?>
📊

Quick Reference

FunctionPurposeExample
preg_match()Check if pattern matches stringpreg_match('/abc/', 'abcdef')
preg_replace()Replace pattern matches in stringpreg_replace('/dog/', 'cat', 'dog and dog')
preg_match_all()Find all matches of patternpreg_match_all('/a/', 'banana', $matches)
preg_split()Split string by patternpreg_split('/,\s*/', 'a, b, c')

Key Takeaways

Use preg_match() to test if a regex pattern matches a string in PHP.
Always enclose regex patterns in delimiters like slashes (/pattern/).
Escape special characters in patterns to match them literally.
Use preg_replace() to replace parts of strings matching a regex.
Modifiers like 'i' make matching case-insensitive.