1

如何使用 PHP 从字符串中返回前 x 段?它们由 \r\n 分隔,但可以根据需要放入<p></p>标签中。

4

2 回答 2

12
//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);
于 2009-12-12T12:45:29.497 回答
0

如果您在 xml/html 环境中,而不是纯文本,您可能会考虑使用 xml 或 DOM 解析器。我不是 php 人,但这是 php 的示例 dom 解析器:http: //simplehtmldom.sourceforge.net/

通常更加灵活和强大,使用简单的 API,然后自己进行解析。

于 2009-12-12T12:56:15.917 回答