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

在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条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)