我需要拆分由段落标签分隔的文本


I need to split text delimited by paragraph tag

$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";

我需要将上述内容拆分为由段落标签分隔的数组。也就是说,我需要将上述内容拆分为一个包含两个元素的数组:

array ([0] = "this is the first paragraph", [1] = "this is the first paragraph")

删除结束</p>标签,因为我们不需要它们,然后在开始</p>标签时将字符串分解成数组。

$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$text = str_replace('</p>', '', $text);
$array = explode('<p>', $text);

若要查看代码运行,请参阅以下代码板条目。如您所见,此代码将在索引 0 处留下一个空数组条目。如果这是一个问题,那么可以通过在使用数组之前调用array_shift($array)轻松删除它。

对于其他发现这一点的人,不要忘记 P 标签可能具有样式、id 或任何其他可能的属性,因此您可能应该查看以下内容:

$ps = preg_split('#<p([^>])*>#',$input);

这是一个古老的问题,但我在寻找stactverflow答案的一个小时内找不到任何合理的解决方案。如果您有充满 html 标签(p 标签(的字符串,并且如果您想获取段落(或第一段(,请使用 DOMDocument .

$long_description 是一个包含 <p> 标记的字符串。

$long_descriptionDOM = new DOMDocument();
// This is how you use it with UTF-8
$long_descriptionDOM->loadHTML((mb_convert_encoding($long_description, 'HTML-ENTITIES', 'UTF-8')));
$paragraphs = $long_descriptionDOM->getElementsByTagName('p');
$first_paragraph = $paragraphs->item(0)->textContent();

我想这是正确的解决方案。不需要正则表达式。

编辑:您不应该使用正则表达式来解析 HTML。

$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$exptext = explode("<p>", $text);
echo $exptext[0];
echo "<br>";
echo $exptext[1];

////////////////输出/////////////////

这是第一段
这是第一段

试试这段代码:

<?php
$textArray = explode("<p>" $text);
for ($i = 0; $i < sizeof($textArray); $i++) {
    $textArray[$i] = strip_tags($textArray[$i]);
}

如果您的输入有些一致,您可以使用简单的拆分方法,如下所示:

 $paragraphs = preg_split('~(</?p>'s*)+~', $text, PREG_SPLIT_NO_EMPTY);

preg_split将查找<p></p>的组合以及可能的空格,并在那里分隔字符串。

作为不必要的替代方法,您还可以使用查询路径或 phpquery 使用以下方法仅提取完整的段落内容:

 foreach (htmlqp($text)->find("p") as $p) { print $p->text(); }

尝试以下操作:

<?php
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$array;
preg_replace_callback("`<p>(.+)</p>`isU", function ($matches) {
    global $array;
    $array[] = $matches[1];
}, $text);
var_dump($array);
?>

这可以修改,将数组放在一个类中,该类使用添加值方法和 getter 来管理它。

试试这个。

<?php
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$array = json_decode(json_encode((array) simplexml_load_string('<data>'.$text.'</data>')),1);
print_r($array['p']);
?>