Remove Text Between Parentheses PHP

Remove Text Between Parentheses PHP

$string = "ABC (Test1)";
echo preg_replace("/\([^)]+\)/","",$string); // 'ABC '

preg_replace is a perl-based regular expression replace routine. What this script does is matches all occurrences of a opening parenthesis, followed by any number of characters not a closing parenthesis, and again followed by a closing parenthesis, and then deletes them:

Regular expression breakdown:

/  - 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 character that is not a closing parenthesis
\) - Match a closing parenthesis
/ - Closing delimiter

PHP: Best way to extract text within parenthesis?

i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)

$text = 'ignore everything except this (text)';
preg_match('#\((.*?)\)#', $text, $match);
print $match[1];

How to remove text inside brackets and parentheses at the same time with any whitespace before if present?

There are four main points here:

  • String between parentheses can be matched with \([^()]*\)
  • String between square brackets can be matched with \[[^][]*] (or \[[^\]\[]*\] if you prefer to escape literal [ and ], in PCRE, it is stylistic, but in some other regex flavors, it might be a must)
  • You need alternation to match either this or that pattern and account for any whitespaces before these patterns
  • Since after removing these strings you may get leading and trailing spaces, you need to trim the string.

You may use

$string = "Deadpool 2 [Region 4](Blu-ray)";
echo trim(preg_replace("/\s*(?:\[[^][]*]|\([^()]*\))/","", $string));

See the regex demo and a PHP demo.

The \[[^][]*] part matches strings between [ and ] having no other [ and ] inside and \([^()]*\) matches strings between ( and ) having no other parentheses inside. trim removes leading/trailing whitespace.

Regex graph and explanation:

Sample Image

  • \s* - 0+ whitespaces
  • (?: - start of a non-capturing group:

    • \[[^][]*] - [, zero or more chars other than [ and ] (note you may keep these brackets inside a character class unescaped in a PCRE pattern if ] is right after initial [, in JS, you would have to escape ] by all means, [^\][]*)
    • | - or (an alternation operator)
    • \([^()]*\) - (, any 0+ chars other than ( and ) and a )
  • ) - end of the non-capturing group.

Remove newline from the text between parentheses

You can use below regex:

(.*\(.*?)(?:\n)(.*?\).*)

Demo: https://regex101.com/r/8XWPrW/4/

Test String:

lorum (ip
sum) dolor

lorum ip
sum dolor

After substitution:

lorum (ipsum) dolor

lorum ip
sum dolor

Also, as required, it will only detect new line when it is within parentheses

-- EDIT--

As discussed in the comments, it will work fine with preg_replace as well. It's just the groups needs to be mentioned

PHP code:

$data="lorum (ip
sum) dolor

lorum ip
sum dolor";
echo preg_replace("'(.*?\(.*?)(?:\n)(.*?\).*)'", "$1$2", $data);

Remove text outside of [] {} () bracket

If the values in the string are always an opening bracket paired up with a closing bracket and no nested parts, you can match all the bracket pairs which you want to keep, and match all other character except the brackets that you want to remove.

(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|[^][(){}]+

Explanation

  • (?: Non capture gorup
    • \[[^][]*] Match from [...]
    • | Or
    • \([^()]*\) Match from (...)
    • | Or
    • {[^{}]*} Match from {...}
  • ) Close non capture group
  • (*SKIP)(*F)| consume characters that you want to avoid, and that must not be a part of the match result
  • [^][(){}]+ Match 1+ times any char other than 1 of the listed

Regex demo | Php demo

Example code

$re = '/(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|[^][(){}]+/m';
$str = 'Hello [123] {45} world (67)
Hello There (8) [9] {0}';

$result = preg_replace($re, '', $str);

echo $result;

Output

[123]{45}(67)(8)[9]{0}

If you want to remove all other values:

(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|.

Regex demo

How to clear text between parentheses with a regular expression in PHP?

You could make the final closing parentheses optional:

preg_replace('/\([^)]+\)?/', '', $myString);
^


Related Topics



Leave a reply



Submit