正则表达式用于报价标签 php



我需要用php解析单引号文本(注意多个嵌套=单),类似于论坛引用标签。例:

some nonquoted text1
[quote="person1"]some quoted text11[/quote]
some nonquoted text2
[quote="person2"]some quoted text22[/quote]
etc... with no newlines necessarily...

结果应该是类似数组的

 Array
        (
            ['nonquoted'] => Array
                (
                    [0] => some unquoted text1
                    [1] => some unquoted text2
                )
            ['quoted'] => Array
                {
                    [0] => Array
                        (
                            [0] => person1
                            [1] => some quoted text11
                        )
                    [1] => Array
                        (
                            [0] => person2
                            [1] => some quoted text22
                        ) 
                 }
        }
$input= <<<EOL
some nonquoted text1
[quote="person1"]some quoted text11[/quote]
some nonquoted text2
[quote="person2"]some quoted text22[/quote]
EOL;
$result = Array('unquoted'=>Array(), 'quoted'=>Array());
//find [quote] blocks, replace them with nothing, and store the text in $result['quoted']
$unquoted = preg_replace_callback('@[quote="([^"]+)"](.*)[/quote]@',function($m) use(&$result){
    $result['quoted'][]=Array($m[1],$m[2]);
},$input);
//what's left is only unquoted lines, so split them into an array
$result['unquoted']=preg_split('@[rn]+@',$unquoted);
//your result
print_r($result);

最新更新