php
  1. php-preg-replace-function

PHP preg_replace() Function

The preg_replace() function in PHP is used to perform a regular expression search and replace operation on a string. It searches a string for patterns that match a regular expression and replaces them with a given substitution string.

Syntax

preg_replace($pattern, $replacement, $subject);
  • $pattern: The regular expression pattern to be searched in $subject.
  • $replacement: The string that will replace the matched pattern.
  • $subject: The string to be searched for the pattern.

Example

$string = "The quick brown fox jumps over the lazy dog.";
$pattern = "/brown/i";
$replacement = "red";
$new_string = preg_replace($pattern, $replacement, $string);
echo $new_string;

Output

The quick red fox jumps over the lazy dog.

Explanation

In the above example, we are using the preg_replace() function to search for the pattern "brown" (case-insensitive) in the string "The quick brown fox jumps over the lazy dog" and replace it with the word "red". The resulting string is "The quick red fox jumps over the lazy dog".

Use

The preg_replace() function is mainly used for pattern matching and string replacement operations in PHP. Some common use cases of this function include:

  • Replacing one or more occurrences of a particular character or pattern in a string.
  • Cleaning up HTML or XML tags from a string.
  • Converting a string from one format to another using regular expressions.

Important Points

Here are some important points to keep in mind when using the preg_replace() function:

  • The $pattern parameter is a regular expression that defines what part of the string to replace.
  • The $replacement parameter is the string that will replace the matched pattern.
  • The $subject parameter is the string to be searched for the pattern.
  • The function returns the modified string.

Summary

The preg_replace() function is a powerful tool in PHP for performing pattern matching and string replacement operations. It allows developers to search for specific patterns in a string and replace them with a given substitution string. Understanding how to use regular expressions and the syntax of the preg_replace() function is key to effectively using this function and improving the functionality of your PHP code.

Published on: