How can regular expressions be used to search for and replace specific patterns in a text string in PHP?

Regular expressions can be used in PHP to search for specific patterns in a text string using functions like preg_match() or preg_match_all(). To replace specific patterns in a text string, the preg_replace() function can be used. This function takes a regular expression pattern to search for and a replacement string to replace the matched patterns.

$text = "Hello, my name is John. I like apples.";
$pattern = "/John/";
$replacement = "Jane";

$new_text = preg_replace($pattern, $replacement, $text);

echo $new_text;