dongzhukuai8177 2013-08-05 15:02
浏览 58
已采纳

像这样的正则表达式模式和返回数组

i want to return array from string like wordpress short code does , but i want the array to be like the example

i have this string

$str = 'codes example : [code lang="php"]<?php  echo "Hello Wold" ; ?>[/code]  [code lang="html"]<b>Hello</b>[/code]' ;

and i want to return contain

array(
   array(
     'code' => '[code lang="php"]<?php  echo "Hello Wold" ; ?>[/code]' ,
     'function' => 'code' ,
     'attr' => array( 'lang' => 'php' ) ,
     'value' => '<?php  echo "Hello Wold" ; ?>'
   ) ,
   array(
     'code' => '[code lang="html"]<b>Hello</b>[/code]' ,
     'function' => 'code' ,
     'attr' => array( 'lang' => 'html' ) ,
     'value' => '<b>Hello</b>'
   )
)

i tried to do it using preg_match_all

i used this pattern /[[a-z]{3,}+ *[a-z]{2,}=(.*)+ *](.*)[\/[a-z]{3,}]/U

and the result was

Array ( [0] => Array ( [0] => [link href="http://www.php.net" text="php"][/link] [1] => [code lang="php"][/code] [2] => [code lang="html"]Hello[/code] ) [1] => Array ( [0] => " [1] => " [2] => " ) [2] => Array ( [0] => [1] => [2] => Hello ) )

  • 写回答

3条回答 默认 最新

  • dongwuge6201 2013-08-05 22:34
    关注

    You can try something like this:

    preg_match_all(
        '#(?P<block>\[(?P<tag>[a-z]{3,})\s*(?P<attr>[a-z-_]+="[^\]]+")*\](?P<content>((?!\[/(?P=tag)).)*)\[/(?P=tag){1}\])#',
        'codes example : [code lang="php" test="true"]<?php  echo "Hello Wold" ; ?>[/code] [code lang="js"]console.log(\'yeah!\')[/code] [noattr]no attr content[/noattr]',
        $matches,
        PREG_SET_ORDER
    );
    foreach ($matches as &$match) {
        $match = array_intersect_key($match, array_flip(array('block', 'tag', 'attr', 'content')));;
    }
    print_r($matches);
    

    result should be:

    Array
    (
        [0] => Array
            (
                [block] => [code lang="php" test="true"]<?php  echo "Hello Wold" ; ?>[/code]
                [tag] => code
                [attr] => lang="php" test="true"
                [content] => <?php  echo "Hello Wold" ; ?>
            )
    
        [1] => Array
            (
                [block] => [code lang="js"]console.log('yeah!')[/code]
                [tag] => code
                [attr] => lang="js"
                [content] => console.log('yeah!')
            )
    
        [2] => Array
            (
                [block] => [noattr]no attr content[/noattr]
                [tag] => noattr
                [attr] =>
                [content] => no attr content
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?