douduan5086 2017-03-30 14:32
浏览 43
已采纳

Ul标签。 如何使用Regex识别列表的开头和结尾

I have a lot of different blog posts in a database. They are in markdown. I want to convert them to html. I have problems with the ul tag.

For instance in a simplified way I have that:

Something
- First
- Second
Something else

Second ul
- First
- Second
Some final text

I could put the li tags:

$text = preg_replace("/^- (.*)/m", "<li>$1</li>", $text);

But how can I identify the beginning or end of the list to put the ul tag?

I want this result:

Something
<ul>
<li>- First</li>
<li>- Second</li>
</ul>
Something else

Second ul
<ul>
<li>- First</li>
<li>- Second</li>
</ul>
Some final text
  • 写回答

1条回答 默认 最新

  • dtqf81594 2017-03-30 15:11
    关注

    You need to do this in two passes, so with two preg_replace calls:

    $text = preg_replace("/^- (.*)/m", "<li>$1</li>", 
                preg_replace("/^- .*(\R- .*)*/m", "<ul>
    $0
    </ul>", $text)
            );
    

    The inner one executes first, and finds lines that starts with - and captures all the following lines that also start with - until the line that follows does not start -.

    .* matches anything up to the end of the current line. The new line character is not matched by .. So the next \R is used for matching anything considered a linebreak sequence. And then again the hyphen check is done and the remainder of the line is captured. This can repeat (( ... )*) as many times as possible.

    That matched block is then wrapped in an ul tag. The hyphens are not removed at this stage.

    The outer one will wrap lines that start with - in li tags, taking out the -.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python如何在已有绘图中添加地图底图
  • ¥15 Tradingview两个副图指标叠加后。在不同的时间框架,和不同的产品,数值参数差异。导致可视化效果
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路
  • ¥15 内网办公电脑进行向日葵
  • ¥15 如何输入双曲线的参数a然后画出双曲线?我输入处理函数加上后就没有用了,不知道怎么回事去掉后双曲线可以画出来