【发布时间】:2009-12-12 20:56:15
【问题描述】:
如何使用 PHP 从字符串中返回前 x 段?它们由 \r\n 分隔,但如果需要,可以放入 <p></p> 标签中。
【问题讨论】:
标签: php paragraphs
如何使用 PHP 从字符串中返回前 x 段?它们由 \r\n 分隔,但如果需要,可以放入 <p></p> 标签中。
【问题讨论】:
标签: php paragraphs
//split $s into paragraphs
$a = explode("\r\n", $s);
//extract the first $x paragraphs only
$a = array_slice($a, 0, $x);
//rejoin the paragraphs into a single string again
$s = implode('\r\n', $a);
【讨论】:
如果您在 xml/html 环境中,而不是纯文本,您可能会考虑使用 xml 或 DOM 解析器。我不是 php 人,但这是 php 的示例 dom 解析器:http://simplehtmldom.sourceforge.net/
通常更加灵活和强大,使用简单的 API,然后自己进行解析。
【讨论】: