douyouming9180 2010-03-15 00:07
浏览 51
已采纳

正则表达式帮助 - 括号内的括号

I'm trying to develop a function that can sort through a string that looks like this:

Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air. 

What I intend to do is search the text recursively for {} patterns where there is no { or } inside the {}, so only the innermost sandwiched text is selected, where I will then run a php to array the contents and select one at random, repeating process until the whole string has been parsed, showing a complete sentence.

I just cannot wrap my head around regular expressions though.

Appreciate any help!

  • 写回答

5条回答 默认 最新

  • doufubian3479 2010-03-15 01:02
    关注

    Regular expressions don't deal well with recursive stuff, but PHP does:

    $str = 'Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air.';
    
    echo parse_string($str), "
    ";
    
    function parse_string($string) {
        if ( preg_match('/\{([^{}]+)\}/', $string, $matches) ) {
            $inner_elements = explode('|', $matches[1]);
            $random_element = $inner_elements[array_rand($inner_elements)];
            $string = str_replace($matches[0], $random_element, $string);
            $string = parse_string($string);
        }
        return $string;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?