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 space using PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
See more codes...