Php 我需要拆分由段落标记分隔的文本
请尝试以下代码:Php 我需要拆分由段落标记分隔的文本,php,html,arrays,querypath,phpquery,Php,Html,Arrays,Querypath,Phpquery,请尝试以下代码: array ([0] = "this is the first paragraph", [1] = "this is the first paragraph") 如果您的输入有点一致,您可以使用简单的拆分方法,如下所示: <?php $textArray = explode("<p>" $text); for ($i = 0; $i < sizeof($textArray); $i++) { $textArray[$i] = strip_ta
array ([0] = "this is the first paragraph", [1] = "this is the first paragraph")
如果您的输入有点一致,您可以使用简单的拆分方法,如下所示:
<?php
$textArray = explode("<p>" $text);
for ($i = 0; $i < sizeof($textArray); $i++) {
$textArray[$i] = strip_tags($textArray[$i]);
}
移除结束标记,因为我们不需要它们,然后在开始标记时将字符串分解成数组
foreach (htmlqp($text)->find("p") as $p) { print $p->text(); }
$text=“这是第一段这是第一段”;
$text=str_replace(“”,“$text”);
$array=分解(“”,$text);
要查看代码运行,请参阅以下内容。如您所见,此代码将在索引0处留下一个空数组项。如果这是一个问题,则可以在使用阵列之前通过调用array\u shift($array)
轻松删除该问题。尝试以下操作:
$text = "<p>this is the first paragraph</p><p>this is the first paragraph</p>";
$text = str_replace('</p>', '', $text);
$array = explode('<p>', $text);
这可以修改,将数组放入一个类中,该类使用一个add-value方法和一个getter来管理它。试试这个
<?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);
?>
$text=“这是第一段这是第一段”;
$exptext=分解(“”,$text);
echo$exptext[0];
回声“
”;
echo$exptext[1];
////////////////输出/////////////////
这是第一段
这是第一段对于任何其他发现这一点的人来说,不要忘记p标记可能有样式、id或任何其他可能的属性,因此您可能应该看到以下内容:
$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];
$ps=preg_split('#]*)*>#',$input);
这是一个老问题,但我在寻找stactverflow答案的一个小时内找不到任何合理的解决方案。如果您的字符串中充满了html标记(p标记),并且如果您想获取段落(或第一段),请使用DOMDocument
$long\u description
是一个包含
标记的字符串
$ps = preg_split('#<p([^>])*>#',$input);
我想这是正确的解决方案。不需要正则表达式
编辑:不应使用正则表达式解析HTML。分解(“”,$text)代码>?@devdRew第一个和最后一个呢?第一个之前没有结束标记,最后一个之后没有开始标记。(感谢它现在已经7岁了)这是最好的答案,因为它说明了是可选的@是的,代码可以缩短为一行,但是跨多行更容易阅读和理解。我尽量让我的答案尽可能清楚,这样所有级别的PHP用户都能理解我想要实现的目标。我同意你的答案是好的explained@Treffynnon:+1这个PHP新手非常欣赏将代码分成多行的可读性。
<?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']);
?>
$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];
$ps = preg_split('#<p([^>])*>#',$input);
$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();