I have to check several strings...the format of each string could be the following:
I-IVWM_Ask-21_(max_2h)
or
D-7849_DG303_(max_4h)
or
Aliante_Privato
I need to capture text in brackets, first part of string outside brackets and replace underscore with spaces.
I'm tring to use preg_match in PHP, as follow
preg_replace('/\([^)]*\)|[()]/', '', $string);
The code above remove string and brackets but leave underscore and doesn't capture the string inside brackets.
Any help to figure out my issue? Thanks
What you might do is first match the pattern, and for the match replace the parenthesis and underscores with a space using preg_replace_callback.
Pattern to match the strings:
^[^\s()]+(?:\([^()]*\))?$
^ Start of string[^\s()]+ Match 1+ chars other than parenthesis or whitespace chars(?:\([^()]*\))? Optionally match the part between parenthesis$ End of stringFor example
$strings = [
"I-IVWM_Ask-21_(max_2h)",
"D-7849_DG303_(max_4h)",
"Aliante_Privato"
];
foreach ($strings as $str) {
$pattern = "/^[^\s()]+(?:\([^()]*\))?$/";
echo preg_replace_callback($pattern, function ($x) {
return trim(preg_replace("/[()_]+/", " ", $x[0]));
}, $str) . PHP_EOL;
}
Output
I-IVWM Ask-21 max 2h
D-7849 DG303 max 4h
Aliante Privato
$strings = [
"I-IVWM_Ask-21_(max_2h)",
"D-7849_DG303_(max_4h)",
"Aliante_Privato"
];
$result = array_map('trim', preg_filter('~[_()]+~', ' ', $strings));