FILTER_VALIDATE_REGEXP constant in PHP

The FILTER_VALIDATE_REGEXP constant validates a value against a Perl-compatible regular expression. It returns the validated value if the pattern matches, or FALSE on failure.

Syntax

filter_var($value, FILTER_VALIDATE_REGEXP, $options)

Parameters

  • $value − The string to validate

  • $options − An array containing the "regexp" key with the pattern to match against

Return Value

Returns the validated string if it matches the pattern, or FALSE if validation fails.

Example 1: Basic Pattern Matching

This example validates an email domain pattern ?

<?php
   $val = "example.com"; 
   $options = array("options" => array("regexp" => "/^ex(.*)/"));
   
   if(filter_var($val, FILTER_VALIDATE_REGEXP, $options)) {
      echo "Matched String!";
   } else {
      echo "Not a Matched String!";
   }
?>
Matched String!

Example 2: Phone Number Validation

Validating a US phone number format ?

<?php
   $phone = "123-456-7890";
   $pattern = array("options" => array("regexp" => "/^\d{3}-\d{3}-\d{4}$/"));
   
   $result = filter_var($phone, FILTER_VALIDATE_REGEXP, $pattern);
   
   if($result) {
      echo "Valid phone number: " . $result;
   } else {
      echo "Invalid phone number format!";
   }
?>
Valid phone number: 123-456-7890

Conclusion

FILTER_VALIDATE_REGEXP provides powerful pattern matching for input validation. Always use proper regex delimiters and escape special characters in your patterns for accurate validation.

Updated on: 2026-03-15T07:33:50+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements