Using the code below, I can turn Number123(45)
into Number
.
$string = 'Number123(45)';
$string2 = preg_replace('/[0-9]+/', '', $string);
echo $string2;
How would I only remove the numbers inside parentheses (brackets) so that the output is Number123()
?
Method 1: We will use sub() method of re library (regular expressions). sub(): The functionality of sub() method is that it will find the specific pattern and replace it with some string. This method will find the substring which is present in the brackets or parenthesis and replace it with empty brackets.
Use re. sub() to remove text within parentheses Call re. sub(pattern, replacement, string) with pattern as the regular expression r"\([^()]*\)" and replacement as "" to remove text within parentheses in string .
Using the replace() Function to Remove Parentheses from String in Python. In Python, we use the replace() function to replace some portion of a string with another string. We can use this function to remove parentheses from string in Python by replacing their occurrences with an empty character.
Include the parentheses in the pattern, like so:
$string = 'Number123(45)';
$string2 = preg_replace('/\([0-9]+\)/', '()', $string);
echo $string2;
Output:
Number123()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With