Loading...

TapGen

Free online tutorials

img

preg_replace in PHP is a function used for performing a search and replace using regular expressions. in this TapGen tutorial we will learn preg_replace function in PHP.

Syntax

preg_replace(patterns, replacements, input, limit, count)

 

Here’s a simple Example

that replaces all occurrences of "dog" with "cat":

                                        
$subject = "The dog barks at the dog.";
$pattern = "/dog/";
$replacement = "cat";

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

echo $result; 
 
                                    
// Output: "The cat barks at the cat."

 

See the example, dog has been replaced by preg_replace Function. that's mean, $pattern: The pattern to search for a string or an array of patterns.

Parameters and Usage

  • $pattern: The pattern to search for. This can be a string or an array of patterns. It must be a valid regular expression.
  • $replacement: The replacement string or an array of replacement strings. If the pattern is an array, this should also be an array of replacements.
  • $subject: The input string or an array of strings to search.

Notes

  • The regular expression patterns must be enclosed in delimiters (e.g., slashes /).
  • You can use various regex features.
  • Be cautious with special characters in both patterns and replacements.

 

If you have any other questions or need further examples, let us know and upload the question in our forum tapgen.xyz

Learn to code with the world's largest web developer site. Not sure where to begin? HTML is The language for building web pages Learn HTML Tutorial with Tapgen.

=================================
Share This Article
icon

New to Communities?

Join the community