在每个段落中创建第一句话 by referencing two break tags and the next period, question mark, or exclamation mark

问题描述 投票:1回答:1

我正在尝试在给定文档的每个段落中的第一个句子之后插入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 />.!?之间的每个句子成为<h3>标签内的文本。所以以<h3>Lorem ipsum.</h3>的格式

php replace strpos punctuation html-heading
1个回答
0
投票

要将替换应用于每个新段落(两个中断标记之后的内容或句子的开头,匹配这些出现,然后使用\K“重新开始匹配”。然后匹配不在标点列表中的零个或多个字符然后一个句子-ending标点符号.$0是匹配的子字符串,用于替换字符串,因此实际上不会丢失任何内容。

代码:(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>$0</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!
© www.soinside.com 2019 - 2024. All rights reserved.