How can preg_replace_callback be used to overcome limitations in PHP string replacement functions?
PHP string replacement functions like `str_replace` or `preg_replace` have limitations when it comes to more complex replacements or dynamic content. `preg_replace_callback` can be used to overcome these limitations by allowing you to define a callback function that processes the matches found in the input string and returns the replacement value.
$input_string = "Hello, my name is [NAME] and I am [AGE] years old.";
$replacements = [
'NAME' => 'John',
'AGE' => 30
];
$output_string = preg_replace_callback('/\[(.*?)\]/', function($matches) use ($replacements) {
$key = $matches[1];
return isset($replacements[$key]) ? $replacements[$key] : $matches[0];
}, $input_string);
echo $output_string;
Related questions
-
fgetcsv PHP CSV
-
CSS stylesheets integration
-
$_POST $_FILES image files