如何使用正则表达式替换圆括号的任何括号?

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

代码如下:

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

它根本没有替换那个字符串...还有比这更好的编码吗?

谢谢。

{[< 永远不会出现在您的字符串中。使用字符 class 或可选分组。

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

替代非字符class方法:

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

https://3v4l.org/URvcb

您可以使用

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

这里,

  • [{[<] - 匹配以下三个字符之一的 character class{[<
  • []}>] - 匹配三个字符之一:]}>(请注意字符 [=47= 中的 ] ] 当它是 class).
  • 中的第一个字符时不必转义

参见PHP demo

您也可以对 preg_replace_callback 进行一次调用:

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

参见 this PHP demo

([{[<]) 模式将开头的标点符号捕获到组 1 ($m[1]) 中,如果找到匹配项后组不为空,则返回 (,否则,) 替换为.

除非您需要正则表达式,否则请避免使用它们。这可以通过简单的字符串替换来完成,例如

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

这里不需要正则表达式:

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

或调用一次 strtr 但数组会更长。