douxuanwei1980 2009-12-12 04:17
浏览 32
已采纳

关于定义列表的正则表达式问题redux

Trying to figure out a way to throw out attributes in this data that do not have any values. Thanks for helping.

My current regex code , thanks to Tomalak looks like this

Regex find

([^=|]+)=([^|]+)(?:\||$)

Regex replace

<dt>$1</dt><dd>$2</dd>

Data looks like this

Bristle Material=|Wire Material=Steel|Dia.=4 in|Grit=|Bristle Diam=|Wire Size=0.0095 in|Arbor Diam=|Arbor Thread - TPI or Pitch=1/2 - 3/8 in|No. of Knots=|Face Width=1/2 in|Face Plate Thickness=7/16 in|Trim Length=7/8 in|Stem Diam=|Speed=6000 rpm [Max]|No. of Rows=|Color=|Hub Material=|Structure=|Tool Shape=|Applications=Cleaning rust, scale and dirt, Light Deburring, Edge Blending, Roughening for adhesion, Finish preparation prior to plating or painting|Applicable Materials=|Type=|Used With=Straight Grinders, Bench/Pedestal Grinders, Right Angle Grinders|Packing Type=|Quantity=1 per pack|Wt.=

End result should like this

 <dt>Wire Material</dt><dd>Steel</dd><dt>Dia.</dt><dd>4 in</dd><dt>Wire Size</dt><dd>0.0095 in</dd>

Not this

 Bristle Material=|<dt>Wire Material</dt><dd>Steel</dd><dt>Dia.</dt><dd>4 in</dd>Grit=|Bristle Diam=|<dt>Wire Size</dt><dd>0.0095 in
  • 写回答

3条回答 默认 最新

  • 普通网友 2009-12-12 05:05
    关注

    Here is how you can do it in PHP without using regular expressions:

    $parts_list = explode('|', "Bristle Material=|Wire M....");
    $parts      = "";
    
    foreach( $parts_list as $part ){
        $p = explode('=', $part);
        if(!empty($p[1])) $parts .= "<dt>$p[0]</dt>
    <dd>$p[1]</dd>
    ";
    }
    
    echo $parts;
    

    And here is how you can do it with regular expressions:

    $parts = preg_replace( 
        array('/([^=|]*)=(?:\||$)/','/([^=|]*)=([^|]+)(?:\||$)/'),
        array('', '<dt>$1</dt><dd>$2</dd>'),
        $inputString 
    );
    
    echo $parts;
    

    Update

    This is using a special replace feature of the PHP preg_replace which takes an array of regex expressions, and an array of replacement strings. The array() syntax of the function basically equates to this:

    If I can match this: /([^=|]*)=(?:\||$)/ then replace it with an empty string.
    If I can match this: /([^=|]*)=([^|]+)(?:\||$)/ then replace it with <dt>$1</dt><dd>$2</dd>

    To test it in a Regex editor, you would run the first expression first (/([^=|]*)=(?:\||$)/) then run the second expression on the result of the first expression.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器