Skip to content
PHP Logo

How can preg_match be used to replace specific characters within parentheses?

To replace specific characters within parentheses using preg_match in PHP, you can use capturing groups in the regular expression pattern to match the content within the parentheses. You can then use the preg_replace function to replace the specific characters within the captured group.

php
$string = "Hello (World)";
$pattern = '/\((.*?)\)/'; // Match content within parentheses
$replacement = 'Universe'; // Replace content within parentheses with this string
$newString = preg_replace($pattern, $replacement, $string);

echo $newString; // Output: Hello Universe