php - 在 Wordpress 中,如何在每篇文章的第一个 h2 标记之后获得直接段落?
问题描述
如何定位每个帖子中第一个 h2 标签后的直接段落?(它们以特定的方式构建)
<!-- Example 1 -->
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<h2>Title</h2>
<p>Lorem Ipsum</p><!-- PHP gets this paragraph -->
<p>Lorem Ipsum</p>
<!-- Example 2 -->
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<h2>Title</h2>
<p>Lorem Ipsum</p><!-- PHP gets this paragraph -->
<p>Lorem Ipsum</p>
<h2>Title</h2>
<p>Lorem Ipsum</p>
通常我会使用 preg_match 或 preg_split,但 Wordpress 不会使用我可以定位的 p 标签存储 post_content,所以这似乎不可行。
编辑:
我想出了如何做到这一点,下面的代码有效:
<?php
$texts = preg_split( '/\r\n|\r|\n/', get_the_content() );
// Loop through items
foreach($texts as $text) {
// If $stop has been set true by presence of H2 in previous item, then break after echoing paragraph
if ($stop == true) {
echo $text;
break;
}
// If first h2 present, then set $stop to true to stop loop after next item
if (strpos($text, 'h2')) {
$stop = true;
}
}
解决方案
继我的评论之后,使用simplexml_load_string
$str = '
<div>
<p>Lorem Ipsum1</p>
<p>Lorem Ipsum2</p>
<h2>Title</h2>
<p>Lorem Ipsum3</p><!-- PHP gets this paragraph -->
<p>Lorem Ipsum4</p>
<h2>Title</h2>
<p>Lorem Ipsum5</p>
</div>';
$xml = simplexml_load_string($str);
$headings = $xml->xpath('h2');
$contents = [];
foreach ($headings as $heading) {
$contents[] = (string)$heading->xpath('following-sibling::p')[0];
}
推荐阅读
- javascript - 如何在本地存储中获取多个项目
- node.js - NatsError:无法连接到服务器:错误:连接 ECONNREFUSED 错误
- matplotlib - 如何从 BinaryClassificationEvaluator 获得的指标中绘制 Pyspark 中的精确召回曲线?
- python - Python 使用 MCP3008 采样频率
- javascript - 如何解决 mongodb altlas 中的 UnhandledPromiseRejectionWarning?
- java - 如何在 Java 中从 jar 创建文件/文件夹?
- powershell - 如何在启动时启动永久运行的 powershell 5.1 脚本?
- sql-server - Always Encryption 功能是否仅适用于 SQL Server?在数据传输到客户端期间如何加密数据?
- validation - 关于 .net 核心实体框架 5 中带有希伯来语后者字段验证的 Url 的问题
- python - 尽管其中存在密钥,但字典不返回任何内容