PHP Regex (Regular Expressions)

What is Regex?

Regular expressions are used to match patterns in strings for validation, search, and replace operations.

preg_match()

Checks if a pattern matches a string (returns 1 if match, 0 if not):

$email = "test@example.com";
if (preg_match("/^[\w.-]+@[\w.-]+\.\w+$/", $email)) {
  echo "Valid email";
}

preg_replace()

Replaces matched patterns in a string:

$text = "I like cats.";
$newText = preg_replace("/cats/", "dogs", $text);
echo $newText;  // I like dogs.

Regex Modifiers

  • i – Case-insensitive
  • m – Multiline mode
  • u – Unicode support
  • s – Dot matches newlines
preg_match("/php/i", "PHP is great");  // Match

Common Patterns

  • \\d – digit
  • \\w – word character
  • . – any character
  • ^ – start of string
  • $ – end of string
  • *, +, ? – quantifiers
preg_match("/^\d{3}-\d{2}-\d{4}$/", "123-45-6789");

Using with Forms

if (preg_match("/^[a-zA-Z ]+$/", $_POST['name'])) {
  echo "Valid name";
} else {
  echo "Invalid name";
}

Error Handling

preg_last_error() returns error codes after a regex operation fails:

if (preg_last_error() !== PREG_NO_ERROR) {
  echo "Regex error occurred.";
}

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic