What is the difference between preg_replace and preg_replace_callback in PHP?
The main difference between preg_replace and preg_replace_callback in PHP is how they handle the replacement of matched patterns in a string. preg_replace allows you to specify a replacement string or an array of replacement strings, while preg_replace_callback allows you to define a callback function that will be called for each match found, allowing for more complex replacements. Example PHP code snippet:
// Using preg_replace
$string = "Hello, World!";
$newString = preg_replace('/Hello/', 'Hi', $string);
echo $newString; // Output: Hi, World!
// Using preg_replace_callback
$string = "Hello, World!";
$newString = preg_replace_callback('/Hello/', function($matches) {
return strtoupper($matches[0]);
}, $string);
echo $newString; // Output: HELLO, World!