Roomal Jayaratne
Roomal Jayaratne

Reputation: 51

How to remove parentheses and replace "white space" with "-" in php using preg_replace

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

Answers (3)

The fourth bird
The fourth bird

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 chars

Php demo | Regex demo

For 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

Amith
Amith

Reputation: 767

$test = preg_replace('/[[:space:]]+/', '-', $test); # Replace space
$test = preg_replace('/[\(|\)]+/', '', $test);      # Replace parenthesis 

echo $test;

Upvotes: 1

marts
marts

Reputation: 104

$text = 'Huawei MatePad 11 (2021)';
$text = preg_replace('/[(|)]/', '', preg_replace('/\s+/', '-', $text));

echo($text);

Upvotes: 1

Related Questions