PHP Tutorial

PHP Flow Control

PHP Functions

PHP String

PHP Array

PHP Date Time

PHP Object Oriented

Regular Expression

PHP Cookie & Session

PHP Error & Exception handling

MySQL in PHP

PHP File Directory

PHP Image Processing

PHP preg_replace(): Perform A Regular Expression Search And Replace

The preg_replace() function in PHP is used to perform a regular expression search and replace.

Here is a basic tutorial on how to use the preg_replace() function in PHP:

Syntax:

The syntax of preg_replace() is:

preg_replace(mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : array|string|null
  • $pattern: The pattern to search for. It can be a string or an array with strings.
  • $replacement: The string or an array with strings to replace. If this parameter is a string and the $pattern parameter is an array, then this string is used as a replacement for every pattern. If both $pattern and $replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the $replacement array than in the $pattern array, any extra $patterns will be replaced by an empty string.
  • $subject: The string or an array with strings to search and replace. If $subject is an array, then the search and replace is performed on every entry of $subject, and the return value is an array as well.
  • $limit: The maximum possible replacements for each pattern in each $subject string. Defaults to -1 (no limit).
  • &$count: If specified, this variable will be filled with the number of replacements done.

Return Value:

Returns an array if the $subject parameter is an array, otherwise it returns a string.

If no matches are found or if replacements were not performed, then it returns null.

Example:

Here is an example demonstrating how to use preg_replace():

<?php
    $pattern = '/(\b[a-z])/i';
    $replacement = '[$1]';
    $subject = "hello world";

    // using preg_replace()
    $result = preg_replace($pattern, $replacement, $subject);

    // Output: [h]ello [w]orld
    echo $result;
?>

In this example, the $pattern is a regular expression that matches the first letter of each word in the $subject string. The preg_replace() function then replaces each match with the corresponding $replacement, resulting in each first letter of each word being enclosed in square brackets.

Note: The $1 in the replacement string is a backreference to the first (and only) capture group in the pattern, which is the first letter of each word.

  1. Performing regular expression search and replace with preg_replace() in PHP:

    • preg_replace() is used to perform regular expression search and replace in a string.
    $pattern = "/apple/";
    $replacement = "orange";
    $text = "I have an apple.";
    
    $newText = preg_replace($pattern, $replacement, $text);
    
  2. Capturing and replacing matched patterns in PHP preg_replace():

    • Use capturing groups to capture and replace matched patterns.
    $pattern = "/(\d{2})-(\d{2})-(\d{4})/";
    $replacement = "$2/$1/$3";
    $dateString = "12-25-2022";
    
    $newDateString = preg_replace($pattern, $replacement, $dateString);
    
  3. Case-insensitive search and replace with preg_replace() in PHP:

    • Use the i flag for case-insensitive search and replace.
    $pattern = "/apple/i";
    $replacement = "orange";
    $text = "I have an Apple.";
    
    $newText = preg_replace($pattern, $replacement, $text);
    
  4. Using arrays and callbacks with preg_replace() for advanced replacements:

    • Use arrays and callbacks for advanced replacements.
    $pattern = "/(\w+)/";
    $callback = function ($matches) {
        return strtoupper($matches[0]);
    };
    $text = "hello world";
    
    $newText = preg_replace_callback($pattern, $callback, $text);
    
  5. Handling multiple patterns and OR conditions with preg_replace() in PHP:

    • Use the | (pipe) symbol for OR conditions.
    $patterns = ["/apple/", "/orange/"];
    $replacement = "fruit";
    $text = "I have an apple and an orange.";
    
    $newText = preg_replace($patterns, $replacement, $text);
    
  6. Using limit parameter in preg_replace() for controlled replacements:

    • Use the limit parameter to control the number of replacements.
    $pattern = "/apple/";
    $replacement = "orange";
    $text = "I have an apple, apple, and another apple.";
    
    $newText = preg_replace($pattern, $replacement, $text, 2);
    
  7. Error handling and debugging with preg_replace() in PHP:

    • Check for errors using preg_last_error().
    $pattern = "/[a-z/";
    $replacement = "X";
    $text = "Invalid pattern";
    
    $newText = preg_replace($pattern, $replacement, $text);
    
    if ($newText === null) {
        $error = preg_last_error();
        echo "Error: $error";
    }