PHP Regular Expressions

Learn about regular expressions in PHP, their syntax, and how to use them for pattern matching.

What are Regular Expressions?

Regular expressions (regex) are sequences of characters that form a search pattern. They are used for pattern matching within strings, allowing you to search, replace, or validate string content efficiently.

Basic Syntax of Regular Expressions

Here are some basic components of regex syntax:

  • Literal Characters: Characters that match themselves (e.g., a, 1).
  • Metacharacters: Special characters with specific meanings (e.g., ., *, +, ?).
  • Character Classes: Matches any character from a set (e.g., [abc] matches a, b, or c).
  • Anchors: Used to match positions in the string (e.g., ^ for the start, $ for the end).
  • Quantifiers: Specify the number of occurrences (e.g., * for zero or more, + for one or more).

Common PHP Functions for Regular Expressions

PHP provides several functions to work with regular expressions:

  • preg_match: Searches a string for a pattern and returns true if found.
  • preg_match_all: Searches a string for a pattern and returns all matches found.
  • preg_replace: Replaces occurrences of a pattern in a string with a replacement string.
  • preg_split: Splits a string by a regular expression pattern.

Examples

Using preg_match

<?php
$string = "Hello, World!";
$pattern = "/World/";
if (preg_match($pattern, $string)) {
    echo "Pattern found!";
} else {
    echo "Pattern not found.";
}
?>

Using preg_match_all

<?php
$string = "apple, banana, cherry";
$pattern = "/\w+/"; // Match words
preg_match_all($pattern, $string, $matches);
print_r($matches[0]); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry )
?>

Using preg_replace

<?php
$string = "I like cats.";
$pattern = "/cats/";
$replacement = "dogs";
$result = preg_replace($pattern, $replacement, $string);
echo $result; // Outputs: I like dogs.
?>

Using preg_split

<?php
$string = "one, two, three";
$pattern = "/,\s*/"; // Split by comma followed by any whitespace
$result = preg_split($pattern, $string);
print_r($result); // Outputs: Array ( [0] => one [1] => two [2] => three )
?>

Conclusion

Regular expressions are a powerful tool for string manipulation in PHP. They allow for complex pattern matching and validation. Understanding regex syntax and PHP functions can greatly enhance your ability to work with strings effectively.