dougua9165
2019-06-17 18:03 阅读 274
已采纳

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

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    dongxuan1314 dongxuan1314 2019-06-17 18:05

    {[< 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

    点赞 评论 复制链接分享
  • dongwen7380 dongwen7380 2019-06-17 18:06

    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.

    点赞 评论 复制链接分享
  • drsdvwsvo78320812 drsdvwsvo78320812 2019-06-17 18:15

    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, ['{' => '(', '}' => ')', '[' => '(', ']' => ')', '<' => '(', '>' => ')']);
    
    点赞 评论 复制链接分享
  • doudou5023 doudou5023 2019-06-17 18:17

    No need for regex here:

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

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

    点赞 评论 复制链接分享

相关推荐