regular

PHP Regular Expressions

PHP Regular Expressions

Regular expressions are used to search, match, and replace patterns in strings. PHP supports regular expressions using functions like preg_match(), preg_replace(), and preg_split().

Matching Patterns

To check if a pattern matches a string, use preg_match():

      
        <?php
          $pattern = "/\d+/"; // Pattern to match digits
          $string = "Hello 123";
          
          if (preg_match($pattern, $string)) {
            echo "Match found!";
          } else {
            echo "No match found.";
          }
        ?>
      
    

Replacing Patterns

To replace a pattern in a string, use preg_replace():

      
        <?php
          $pattern = "/\d+/";
          $string = "Hello 123";
          $replacement = "XYZ";
          
          $newString = preg_replace($pattern, $replacement, $string);
          echo $newString; // Output: Hello XYZ
        ?>
      
    

Activity

Try It Yourself!

Write a regular expression to match a valid email address and use it to validate an email input from a form.

Quiz

Quick Quiz

  1. Which function is used to match patterns in PHP?
  2. How can you replace a pattern in a string in PHP?

Answers: Use preg_match() to match patterns. Use preg_replace() to replace patterns.