php-regexHow to replace strings using PHP regex?
PHP provides a powerful set of regular expression functions that can be used to replace strings.
$string = 'This is a string';
$pattern = '/string/';
$replacement = 'sentence';
echo preg_replace($pattern, $replacement, $string);
Output example
This is a sentence
The code above uses the preg_replace()
function to replace the string string
with sentence
in the variable $string
. The $pattern
variable contains the regular expression pattern to match the string to be replaced, and the $replacement
variable contains the string to replace it with.
The preg_replace()
function takes three parameters: the regular expression pattern, the replacement string, and the string to be searched. It returns the modified string.
Helpful links
More of Php Regex
- How to match a double quote in PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to match a space using PHP regex?
- How to match a single quote in PHP regex?
- How to use named capture groups in PHP regex?
- How to match the end of a string when using regex in PHP?
- How to use an "or" condition in PHP regex?
- How to get last matched occurrence in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
See more codes...