dsdapobp26141 2015-12-13 02:06
浏览 46
已采纳

在preg_replace()函数中循环遍历ol标记

I am trying to replace new lines of a code with html ol tag to display the code as

1. Line 1
2. Line 2
3. Line 3
4. Line 4

Here is my php

$x="Line 1
      Line 2
      Line 3
      Line 4";

 echo preg_replace("/
+([^
]+)/","<ol start='1'><li>$1</li></ol>",$x);

The problem is ol tag is not looping in the preg_replace() function,so It outputs

1. Line 1
1. Line 2
1. Line 3
1. Line 4

What is wrong with the code?

  • 写回答

2条回答 默认 最新

  • dselp3944 2015-12-13 02:09
    关注

    You are creating multiply ol tags instead of wrapping the ol around the preg_replace function. You can also simplify your regex with the m modifier:

    $x="Line 1 
          Line 2 
          Line 3 
          Line 4";
    
    echo "<ol start='1'>" . preg_replace("/^(.*?)$/m", "<li>$1</li>", $x) . "</ol>";
    

    Alternative if you don't want the trailing newlines simply use:

    /^(.*?)\s?$/m
    

    When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier.

    Source: php.net

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面