通过引用两个分隔标记和下一个句点、问号或感叹号,使每个段落中的第一句成为 <H3>

Make the first sentence in each paragraph an <H3> by referencing two break tags and the next period, question mark, or exclamation mark

我正在尝试在给定文档的每个段落的第一句之后插入一个 HTML 标记。

我想出的代码(我不是程序员)正在运行。

$insert_pos是最后插入标签的位置。之所以需要它,是因为大多数文档中都有不止一个段落。

现在我还需要检查“?” (可能还有“!”)。

$insert_pos = strpos($content, ".", $insert_pos) + 1;
$content= substr_replace( $content, "</tag>", $insert_pos,0 );

一些上下文:

每个 CMS,一个段落是用 </br><br /> 生成的。因此文档将具有以下格式:

 Lorem ipsum dolor sit amet, consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. </br><br />Lorem ipsum. Lorem ipsum dolor sit amet, consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. </br><br />voluptua.

我需要 <br />. OR ! OR ? 之间的每个句子成为 <h3> 标签内的文本。所以格式为 <h3>Lorem ipsum.</h3>

要将替换应用到每个新段落(内容或句子的开头,在两个换行标记之后,匹配这些匹配项,然后使用 \K 到 "restart the match"。然后匹配零个或多个字符不在标点符号列表中然后是句末标点符号。[=13=] 是替换字符串中使用的匹配子字符串,因此不会实际丢失任何内容。

代码:(Demo)

$content = "What in the world? I don't know.<br><br>This is paragraph number 2!  What a fascinating read.<br><br>No matter how many paragraphs, look for one of the three sentence ending punctuations after a fully empty line.  Good stuff!";

$content = preg_replace('~(?:^|<br><br>)\K[^.?!]*[.?!]~', '<h3>[=10=]</h3>', $content);
//                             ^^^^^^^^-- </br><br />  to be more specific
echo $content;

输出:

<h3>What in the world?</h3> I don't know.<br><br><h3>This is paragraph number 2!</h3>  What a fascinating read.<br><br><h3>No matter how many paragraphs, look for one of the three sentence ending punctuations after a fully empty line.</h3>  Good stuff!