PHP regular expression to replace nested () with []

前端 未结 5 1226
感动是毒
感动是毒 2021-01-21 23:25

I am trying to match a string, see example, such that a nested parantheses () is replaced by [] so to not break a parser somewhere else. In this case, I would like to replace t

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 23:57

    $myStr = "Arman; Dario (10040 Druento (Turin), IT)";
    
    $pattern = "/(.*\(.*)\(([^()]+)\)(.*)/";
    if (preg_match_all($pattern,$myStr,$matches))
        {
            print( $matches[1] . '[' . $matches[2] . ']' . $matches[3] );
        }
    

    You can run it through that until it doesn't match

    while( preg_match_all($pattern,$myStr,$matches)) )
    {
        $mystr = $matches[1] . '[' . $matches[2] . ']' . $matches[3];
    }
    

提交回复
热议问题