Home >Backend Development >PHP Tutorial >How to Remove Text Enclosed in Parentheses Using PHP?
Stripping Text from Parentheses in PHP
Question:
How can I eliminate text enclosed in parentheses and the enclosing parentheses itself using PHP?
Example:
Given the input "ABC (Test1)", the desired output is "ABC".
Answer:
preg_replace is a built-in PHP function that allows for powerful string manipulation using regular expressions. Here's how you can achieve the desired result:
<?php $string = "ABC (Test1)"; echo preg_replace("/\([^)]+\)/","",$string); // Output: ABC ?>
Explanation:
preg_replace takes three arguments:
The regular expression pattern in our case is:
/ - Opening delimiter (necessary for regular expressions, can be any character that doesn't appear in the regular expression \( - Match an opening parenthesis [^)]+ - Match 1 or more characters that are not closing parentheses \) - Match a closing parenthesis / - Closing delimiter
This expression matches all instances of an opening parenthesis followed by one or more non-parentheses characters followed by a closing parenthesis. The matched pattern is then deleted, resulting in the desired output.
The above is the detailed content of How to Remove Text Enclosed in Parentheses Using PHP?. For more information, please follow other related articles on the PHP Chinese website!