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:
\([^)]{2,}\)
.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?
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)
){2,}
saying we want to match two or more of these([^\(\)]{2,})
- this will get the entire contents of the parentheses in the string\)
literal closing parenthesisThe second parameter in the preg_replace
call is defining to replace our full match (Additional params)
with the capturing group Additional params
.