In this article, you will learn how to find and replace string in PHP. The preg_replace() function in PHP returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings.
what is the syntax of the PREG_REPLACE function in php?
preg_replace(patterns, replacements, input, limit, count)
|patterns||Required. Contains a regular expression or array of regular expressions|
|replacements||Required. A replacement string or an array of replacement strings|
|input||Required. The string or array of strings in which replacements are being performed|
|limit||Optional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string|
|count||Optional. After the function has executed, this variable will contain a number indicating how many replacements were performed|
examples of the PREG_REPLACE function
Example 1. In this example, we use a case-insensitive regular expression to replace Microsoft with W3Schools in a string.
<?php $str = 'Visit Microsoft!'; $pattern = '/microsoft/i'; echo preg_replace($pattern, 'W3Schools', $str); ?>