PHP regular expressions


Answers ( 1 )


    Regular expressions in PHP are used for pattern matching and text manipulation. PHP provides two main ways to use regular expressions: POSIX-extended and Perl-Compatible Regular Expressions (PCRE).

    Perl-Compatible Regular Expressions (PCRE)

    PCRE functions in PHP have names that start with preg_. Here are some commonly used functions:

    1. preg_match() - This function checks if a pattern matches a string. It's often used for validation.


      if (preg_match("/^[a-zA-Z ]*$/", $name)) {
          echo "Valid name";
      } else {
          echo "Invalid name";
    2. preg_match_all() - Similar to preg_match but finds all matches in a string.


      $text = "cats and dogs";
      preg_match_all("/cats|dogs/", $text, $matches);
    3. preg_replace() - This is used for replacing text using a regular expression.


      $text = "The quick brown fox";
      $newText = preg_replace("/quick/", "slow", $text);
      echo $newText;
    4. preg_split() - Splits a string by a regular expression.


      $data = "one, two, three";
      $parts = preg_split("/, /", $data);

    POSIX-Extended Regular Expressions

    These are less commonly used in PHP and are identified by functions starting with ereg_ (such as ereg() and eregi()). However, as of PHP 5.3.0, these functions are deprecated and should be avoided in favor of PCRE.

    Writing a Regular Expression

    The syntax of regular expressions can be complex, but here are a few basic components:

    • Literals: Plain characters that match themselves.
    • Character classes: Square brackets [] define a set of characters to match.
    • Quantifiers: Symbols like *, +, and ? define how many times an element should be matched.
    • Anchors: ^ and $ specify the start and end of a string, respectively.


    Suppose you want to validate an email address using a regular expression in PHP:

    $email = "";
    if (preg_match("/^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/", $email)) {
        echo "Valid email address";
    } else {
        echo "Invalid email address";

    In this example, the regular expression checks for a pattern that resembles a typical email format.

    Remember that regular expressions are powerful but can be complex, so it's important to test them thoroughly.

Leave an answer