dongwo5589 2016-04-30 03:25
浏览 31
已采纳

PHP括号内容索引在数组中

I want to take the string:

(contents) some text (contents two) more text 

and have it output this array:

array(

[contents] => some text
[contents two] => more text

)

I've tried looping thru it and using array_push

  • 写回答

3条回答 默认 最新

  • duansanzi5265 2016-04-30 03:43
    关注

    The solution using preg_match_all(with named submasks (?<name>)) and array_combine functions:

    $str = '(contents) some text (contents two) more text';
    
    preg_match_all("/\((?<key>.+?)\) (?<value>[^()]+)/iu", $str, $m, PREG_PATTERN_ORDER);
    $result = array_combine($m['key'], $m['value']);
    
    print_r($result);
    

    The output:

    Array
    (
        [contents] => some text 
        [contents two] => more text
    )
    

    Update: For your additional request "make it work if there's no space after the bracket" with the input string "(contents)some text (contents two)more text" : to make it work - change the current regex pattern to as following "/\((?<key>.+?)\)\s?(?<value>[^()]+)/iu"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?