我想从字符串中找到段落,并格式化它们,我有什么样的作品,但它不工作100%.
所以,我有这个字符串,看起来像这样:
##Chapter 1
Once upon a time there was a little girl named sally, she went to school.
One day it was awesome!
##Chapter 2
We all had a parade!
我正在格式化字符串,将##...
转换为<H2>
,它现在看起来像这样:
<h2>Chapter 1</h2>
Once upon a time there was a little girl named sally, she went to school.
One day it was awesome!
<h2>Chapter 2</h2>
We all had a parade!
现在我想把所有内容都转换成一个段落,为此我这样做:
// Converts sections to paragraphs:
$this->string = preg_replace("/(^|\n\n)(.+?)(\n\n|$)/", "<p>$2</p>", $this->string);
// To Remove paragraph tags from header tags (h1,h2,h3,h4,h5,h6,h7):
$this->string = preg_replace("/<p><h(\d)>(.+?)<\/h\d><\/p>/i", "<h$1>$2</h$1>", $this->string);
这是最终的输出(为了可读性添加了新行):
<h2>Chapter 1</h2>
Once upon a time there was a little girl named sally, she went to school.
<p>One day it was awesome!</p>
<h2>Chapter 2</h2>
<p>We all had a parade!</p>
正如我在开头所说的,这并不是100%有效,正如你所看到的,第一段没有添加一段。如何改进正则表达式?
2条答案
按热度按时间iq0todco1#
你可以一步完成:
图案详情
qvsjd97n2#
将m开关添加到第一个正则表达式。