【问题标题】:PHP - format html b tags into header tagsPHP - 将html b标签格式化为标题标签
【发布时间】:2015-02-10 02:06:13
【问题描述】:

我想将多个段落格式化为更好的 html 结构

有一个数据库,其中有一列名为 bodytext $bodytext = $row["bodytext"]; 如果我回应这个,你会得到多个段落

这是一段:

— 开始第 1 段

<b>lorem</b>
description 1

<b>lorem</b>
description 2

<b>lorem</b>
description 3

<b>lorem</b>
description 4

<b>lorem</b>
description 5

<b>lorem</b>
description 6

—结束第 1 段

一个示例段落的最终结果:

— 开始第 1 段

<h1>lorem</h1>
decription 1

<h2>lorem</h2>
description 2

<h2>lorem</h2>
description 3

<h3>lorem</h3>
description 4

<h3>lorem</h3>
description 5

<h3>lorem</h3>
description 6

—结束第 1 段

我想将 b 标签格式化为从 h1 到 h4 的分层标题标签 这意味着 h1 只能存在一次,h2 只能存在 2 次,h3 次,h4 其余的 带文本的标题数量取决于内容,另一个段落只能有三个带文本的标题......

php 最好的方法是什么?

【问题讨论】:

  • 这对于正则表达式是“不可能的”。并排序...阅读此内容:php.net/manual/en/book.xml.php
  • 当然可以,不过您尝试了什么,您的问题是什么?
  • 尝试一些非常复杂的for循环或其他一些循环类型。

标签: php arrays regex sorting


【解决方案1】:

如果你的内容是按照你的例子显示的,你可以使用这个:

$text = ''; // your example text goes here

$i = 1;
$matches = null;

while (true) {

    $text = preg_replace('|<(/)?b>|', ('<\1h'.$i.'>'), $text, 2, $matches);

    if (!$matches) {
        break;        
    }

    if ($i < 4) $i++;
    $matches = null;

}

你可以在这里看到这项工作:

http://ideone.com/ifmmfP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 2017-06-21
    • 2017-05-07
    • 2015-11-20
    • 2020-04-14
    相关资源
    最近更新 更多