How can preg_replace() be used to remove all content within parentheses from a string in PHP?

To remove all content within parentheses from a string in PHP, you can use the preg_replace() function with a regular expression pattern that matches anything within parentheses. The regular expression pattern should look for an opening parenthesis, followed by any characters (including nested parentheses), and a closing parenthesis. By replacing this pattern with an empty string, you can effectively remove all content within parentheses from the string.

$string = "This is a (sample) string with (parentheses)";
$pattern = "/\([^)]*\)/";
$cleaned_string = preg_replace($pattern, "", $string);

echo $cleaned_string; // Output: This is a string with