修剪字符串中第3个'p'标记后的所有内容?

时间:2014-08-19 14:01:32

标签: php strpos

我有以下代码:

$start = strpos($text, '<p>'); // Locate the first paragraph tag
$end = strpos($text, '</p>', $start); // Locate the first paragraph closing tag
$text = substr($text, $start, $end-$start+4); // Trim off everything after the closing paragraph tag

如何修改上述代码以修剪第3个 p标记后的所有内容?

<p>first</p>
<p>second</p>
<p>third</p>
<p>this and next should be removed...</p>

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

此示例基于<p>标记展开文本字符串,然后对于前3个元素,将其重新组合在一起:

<?php

$text = "<p>first</p>
<p>second</p>
<p>third</p>
<p>this and next should be removed...</p>";

$parts = explode ("<p>", $text);



$fin = "";
for ($i = 1; $i < 4; $i++) {
    $fin .= "<p>" . $parts[$i];
}

echo $fin;
?>

返回:

<p>first</p>
<p>second</p>
<p>third</p>