duande3134 2012-01-25 13:36
浏览 38
已采纳

搜索和替换数千行php

I am very new to using preg_replace and such so please bear with me.

I have few hundreds line that contains this line

<strong>[*<a title="*" name="*"></a>]</strong><br /> Lorem ipsum

* on above code denotes that number such as 1,2,3

What i want to achieve is that

*. Lorem Ipsum

Example, 1. Lorem ipsum, 2. Lorem ipsum

What would be the best way to achieve it? Thanks.

sample text

<strong>[1<a title="1" name="1"></a>]</strong><br /> Lorem ipsum 12345<br /> <strong>[2<a title="2" name="2"></a>]</strong><br /> lorem ipsum asdasd<br /> <strong>[3<a title="3" name="3"></a>]</strong><br /> lorem ipsum asdsadasdasdasd<br />

it goes way up to hundreds

  • 写回答

3条回答 默认 最新

  • douzhi9478 2012-01-25 14:07
    关注

    How about:

    $output = preg_replace('~^<strong>\[(\d+)<.*?<br\s*/>~', '$1. ', $input);
    

    explanation:

    ~             : regex delimiter
      ^           : start of line
      <strong>    : <strong> as is
      \[          : an open square bracket
      (\d+)       : capture one or more digits
      <.*?        : > followed by any number of any char
      <br\s*/>    : <br/> or <br />
    ~
    

    And replace all that match by the first captured group (ie. the digits) followed by a dot and a space.

    Edit according to comments:

    $input = '<strong>[1<a title="1" name="1"></a>]</strong><br /> Lorem ipsum 12345<br /> <strong>[2<a title="2" name="2"></a>]</strong><br /> lorem ipsum asdasd<br /> <strong>[3<a title="3" name="3"></a>]</strong><br /> lorem ipsum asdsadasdasdasd<br />';
    $output = preg_replace('~\s*<strong>\[(\d+)<.*?<br\s*/>(.*?)(?:<br />|$)~', "$1. $2
    ", $input);
    echo $output,"
    ";
    

    output:

    1.  Lorem ipsum 12345
    2.  lorem ipsum asdasd
    3.  lorem ipsum asdsadasdasdasd
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度