Reputation: 51
This is What I Have - Huawei MatePad 11 (2021)
This is what I want - Huawei-MatePad-11-2021
This is what I have done so far. (only it replaces "white space" with "-".
echo preg_replace('/[[:space:]]+/', '-', $test);
I want to remove parentheses, and want to replace "white space" with "-" at once. How to do it?
Upvotes: 3
Views: 403
Reputation: 163632
You might also use a single pattern with preg_replace_callback and match from an opening till closing parenthesis.
\(([^()]+)\)|\h+
The pattern matches:
\(
Match (
([^()]+)
Capture group 1 match 1+ chars other than (
)
\)
Match )
|
Or\h+
Match 1 or more horizontal whitespace charsFor example return group 1 using $m[1]
if it exists, else return -
$s = "Huawei MatePad 11 (2021)";
$regex = "/\(([^()]+)\)|\h+/";
$result = preg_replace_callback($regex, function($m) {
return array_key_exists(1, $m) ? $m[1] : '-';
}, $s);
echo $result;
Output
Huawei-MatePad-11-2021
Upvotes: 1
Reputation: 767
$test = preg_replace('/[[:space:]]+/', '-', $test); # Replace space
$test = preg_replace('/[\(|\)]+/', '', $test); # Replace parenthesis
echo $test;
Upvotes: 1
Reputation: 104
$text = 'Huawei MatePad 11 (2021)';
$text = preg_replace('/[(|)]/', '', preg_replace('/\s+/', '-', $text));
echo($text);
Upvotes: 1