mizhko
mizhko

Reputation: 37

How to replace any brackets for rounded brackets using Regular Expression?

Here is code:

$string="{1},[2],(3),<4>";
// Replaces closing square, curly, angle brackets with round brackets
$string = preg_replace('/\{\[\</', '(', $string);
$string = preg_replace('/\}\]\>/', ')', $string);

It didn't replace at all in that string... Any better coding than that?

Thanks.

Upvotes: 1

Views: 1631

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627087

You may use

$string="{1},[2],(3),<4>";
$what = ['~[{[<]~', '~[]}>]~'];
$with = ['(', ')'];
$string = preg_replace($what, $with, $string);
echo $string;

Here,

  • [{[<] - a character class that matches one of the three chars: {, [ or <
  • []}>] - matches one of the three chars: ], } or > (note that ] inside the character class does not have to be escaped when it is the first char in the class).

See the PHP demo.

You may use a single call to preg_replace_callback, too:

$string = preg_replace_callback('~([{[<])|[]}>]~', function ($m) {
    return !empty($m[1]) ? "(" : ")";
 }, $string);

See this PHP demo.

The ([{[<]) pattern captures the opening punctuation into Group 1 ($m[1]) and if the group is not empty after a match is found, ( is returned, else, ) is replaced with.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

No need for regex here:

$string = str_replace(['{','[','<'], '(', str_replace(['}',']','>'], ')', $string));

Or use one call to strtr but the array will be longer.

Upvotes: 2

cmb
cmb

Reputation: 715

Unless you need regular expressions, avoid them. This can be done by simple string replacement, e.g.

<?php
$string = "{1},[2],(3),<4>";
$string = strtr($string, ['{' => '(', '}' => ')', '[' => '(', ']' => ')', '<' => '(', '>' => ')']);

Upvotes: 2

user3783243
user3783243

Reputation: 5224

{[< never occurs in your string. Use a character class or optional grouping.

$string = preg_replace('/[{[<]/', '(', $string);
$string = preg_replace('/[}>\]]/', ')', $string);

Alternative non character class approach:

$string = preg_replace('/(?:\{|<|\[)/', '(', $string);
$string = preg_replace('/(?:\}|>|\])/', ')', $string);

https://3v4l.org/URvcb

Upvotes: 1

Related Questions