Current Location: Home> Latest Articles> Three Common Methods to Remove Parentheses from Strings in PHP

Three Common Methods to Remove Parentheses from Strings in PHP

gitbox 2025-07-29

Three Common Methods to Remove Parentheses from Strings in PHP

In PHP, string manipulation is a common task, especially when you need to remove parentheses from a string. PHP provides several built-in functions to help developers accomplish this. This article will detail three methods: str_replace, preg_replace, and substr functions, to remove parentheses from strings.

Using str_replace to Remove Parentheses

str_replace is one of PHP's built-in functions that can replace characters in a string. To remove parentheses, you can use this function to replace the left and right parentheses in the string. Here's an example:


$str = "hello(php) world!";
$delimiter = array("(", ")");
$result = str_replace($delimiter, "", $str);
echo $result;

In this example, we define a string variable $str containing parentheses. Then, we use the str_replace function to replace the parentheses with an empty string and finally output the result without the parentheses.

Using preg_replace to Remove Parentheses

In addition to str_replace, preg_replace is a very powerful function that allows you to use regular expressions to perform string replacements. With regular expressions, you can more flexibly match parentheses and replace them. Here's an example:


$str = "hello(php) world!";
$result = preg_replace('/[\(\)]/', "", $str);
echo $result;

In the above code, we use the regular expression '/[\(\)]/' to match parentheses and replace them with an empty string. The strength of preg_replace lies in its ability to match any characters that fit the pattern and replace them accordingly.

Using substr to Remove Parentheses (For Symmetrical Parentheses)

If the string contains only one pair of parentheses and the positions are symmetrical, you can use the substr function to remove the parentheses. Here's an example:


$str = "hello(php) world!";
$result = substr($str, 0, strpos($str, "(") ) . substr($str, strpos($str, ")") + 1);
echo $result;

In this example, we use both substr and strpos functions to locate the positions of the parentheses. Then, we use substr to extract the string before the left parenthesis and after the right parenthesis, and finally concatenate the two parts together to get the result without the parentheses.

Summary

With the three methods introduced in this article, you can choose the most appropriate way to remove parentheses from PHP strings based on your needs. Whether using str_replace, preg_replace, or substr, each method can effectively help you achieve the goal of removing parentheses. By selecting the most suitable method for your specific scenario, you can make your code more concise and efficient.