The preg_replace() and preg_split() functions in PHP are powerful tools for manipulating strings using regular expressions. preg_replace() replaces matching patterns, while preg_split() breaks strings into arrays based on patterns.
// Using preg_replace() and preg_split()
<?php
$text = "The quick brown fox jumps over the lazy dog.";
$pattern = "/quick/";
$replacement = "fast";
$new_text = preg_replace($pattern, $replacement, $text);
echo "After replacement: " . $new_text . "<br>";
$string = "apple,banana,grape,orange";
$split_pattern = "/,/";
$fruits = preg_split($split_pattern, $string);
print_r($fruits);
?>
Output Explanation:
Think of preg_replace() as a find-and-replace engine and preg_split() as smart scissors that cut text wherever the pattern matches.