How can regular expressions be used in PHP to replace specific patterns within a string?
Regular expressions can be used in PHP to search for specific patterns within a string and replace them with a different pattern. This can be useful for tasks such as finding and replacing certain characters, words, or formats within a larger text. The preg_replace() function in PHP allows you to specify a regular expression pattern to search for and a replacement string to use when a match is found.
$string = "Hello, my name is John.";
$pattern = '/John/';
$replacement = 'Jane';
$new_string = preg_replace($pattern, $replacement, $string);
echo $new_string; // Output: Hello, my name is Jane.