Search code examples
phpregexpcre

Remove parantheses only if inside characters more than one


I want to remove parantheses only if inside them is more than one character of text.

My input is:

$string = "Model name (4) Color (Additional Params)"

My desired final output string should be: "Model name (4) Color Additional Params".

My solution is:

  1. Detect needed scope with Regex \([^)]{2,}\).
  2. Cut it from original string.
  3. Remove parantheses.
  4. Attach back to original string.

I know that regular expressions have Conditional statements. But I can't understand logic of using them.

Is it possible to do with single regex and how?


Solution

  • It is possible to do with one regex:

    $string = 'Model name (4) Color (Additional Params) and some other (a) with more (params)';
    $modifiedString = preg_replace('/\(([^\(\)]{2,})\)/', '$1', $string);
    var_dump($modifiedString);
    

    This will give:

    string(74) "Model name (4) Color Additional Params and some other (a) with more params"

    Pattern explained:

    • \( - match literal opening parenthesis
    • [^\(\)] - match any character that is not either an opening or closing parenthesis (we need to do this so it wouldn't match everything between the first opening and last closing parenthesis - (4) Color (Additional Params))
    • it is followed by a quantifier {2,} saying we want to match two or more of these
    • together with the quantifier it is wrapped in parentheses, forming a capturing group: ([^\(\)]{2,}) - this will get the entire contents of the parentheses in the string
    • finally we match \) literal closing parenthesis

    The second parameter in the preg_replace call is defining to replace our full match (Additional params) with the capturing group Additional params.