doubi4435 2018-04-17 19:51
浏览 54
已采纳

字符串缺失分隔符上的单个捕获组的PCRE正则表达式

I have html with this sort of node value:

80% Polyester 10% Cotton 10% Rayon

It can also be like these:

90% Cotton 10% Rayon

Or:

100% Cotton

EDIT -- ALSO the text to capture might be more than one word like:

90% Egyptian Cotton 10% Polyester

What I need to do in PHP is change it to be like:

<li>80% Polyester</li>
<li>10% Cotton</li>
<li>10% Rayon</li>

I'm not sure how to get the capture group quite right... maybe there needs to be two capture groups that can happen 1+ times?

preg_match('/<p>([1-9]?[0-9]?% [^\d<]+|^100% )+<\/p>/', '<p>80% Polyester 10% Cotton 10% Rayon</p>', $matches);

This only finds 1 match for: 10% Rayon... what am I doing wrong for it not to capture all 3 groups?

EDIT: PLEASE FORGET ABOUT THE HTML TAGS

I stripped the tags from the question because people can't get over the whole regex and html issue... think of this as just a data string please.

  • 写回答

3条回答 默认 最新

  • dtsnx44260 2018-04-17 20:09
    关注

    You may use this preg_replace:

    $repl = preg_replace('/([\d.]+%\h*\pL+(?:\h+\pL+)*)\h*/', 
                         '<li>$1</li>
    ', $str);
    

    RegEx Demo

    ([\d.]+%\h*\pL+(?:\h+\pL+)*)\h* matches and groups 1+ digits followed by % followed by 0+ spaces followed by 1+ letter and space characters.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里