根据顺序删除所有段落(在第2、3或4…之后)


Remove all paragraphs based on order (after the 2rd, 3th or 4th...)

我得到了这个

$description =  '<p>text1</p><p>text2</p><p>text3</p><p>text4</p><p>textn</p>'

我只想删除<p>text3</p>

之后的内容

我的结果将是:

$description = '<p>text1</p><p>text2</p><p>text3</p>'

我的猜测是,我们需要使用preg_replace与一些正则表达式,但我不能设法写一个工作的

你可以…

function str_occurance($needle, $haystack, $occurance) { 
$occurance += 2;
$arr = explode($needle, $haystack, $occurance);
unset($arr[0]);
$arr = array_values($arr);
$key = count($arr) - 1;
unset($arr[$key]);
$str = $needle . implode($needle, $arr);
return $str; 
}

不是最漂亮的,但是很好用。

编辑:使用:

$description =  '<p>text1</p><p>text2</p><p>text3</p><p>text4</p><p>textn</p>';
$split = '<p>';
$return = 3;
$new = str_occurance($needle, $description, $return);
echo $new; // returns <p>text1</p><p>text2</p><p>text3</p>