PHP preg_replace() functionThe preg_replace() function is a built-in function of PHP. It is used to perform a regular expression search and replace. This function searches for pattern in subject parameter and replaces them with the replacement. SyntaxParametersThis function accepts five parameters, which are described below: pattern This parameter can be either a string or an array with strings. It holds the pattern to search in subject parameter. replacement It is a string or an array with strings parameter. This parameter replaces the pattern matched in subject parameter. It is a mandatory parameter.
subject The subject parameter can also be either a string or an array of string to search and replace. If the subject is an array, the search and replacement are performed on every entry of subject, and the returned value will also be an array. limit The limit is an optional parameter that specifies the maximum possible replacement for each pattern. The default value of limit is -1, which means no limit. count It is an optional parameter. If this parameter is passed, this variable will contain the number of replacements done. This parameter added in PHP 5.1.0. Return TypeThe preg_replace() function returns an array if the subject parameter is an array otherwise it returns a string.
ExamplesSimple Replacing See the detailed examples to understand the preg_replace() function practically: Example using backreference followed by numeric literals Output: May 5, 2020 Example to strip whitespace In the below example, preg_replace() removes all extra whitespace from the given string. Output: Camila Cabello is a Hollywood singer. Example using indexed arrays This example will contain a pattern array to replace with replacement array. Output: String after replacement: The fox brown quick runs away from the zoo. In the above example, we can see that output is not same as we want. Therefore, by applying ksort() on patterns and replacements before using preg_replace(), we can get what we want to. Output: String after replacement using ksort: The quick brown fox runs away from the zoo.
Next TopicPHP isset() function
|