如何在html片段的X段之后插入一个文本字符串


How to insert a string of text after X paragraphs of an html fragment?

可能重复:
如何使用PHP解析和处理HTML?

$content = "
<p>This is the first paragraph</p>
<p>This is the second paragraph</p>
<p>This is the third paragraph</p>";

给定一个如上所述的html内容字符串,我需要在第N个段落标记后面插入一个内容。

我如何解析内容并插入给定的文本字符串,在第2段后说"你好,世界"?

您可以使用PHP分解和内爆函数。这里有一个概念:

$content = "
<p>This is the first paragraph</p>
<p>This is the second paragraph</p>
<p>This is the third paragraph</p>";
$content_table = explode("<p>", $content);

这将创建具有以下值的$content_table

Array ( [0] => [1] => This is the first paragraph
[2] => This is the second paragraph
[3] => This is the third paragraph
) 

现在,您可以使用$content_table[2]对第2段进行任意更改。例如,你可以做:

$content_table[2] .= "hello world!";

完成后,只需将表内爆以再次字符串:

$content = implode($content_table, "<p>");

如果您确信字符串的HTML结构,您可以在回调的静态变量中计算所看到的段落。

$content = preg_replace_callback('#(<p>.*?</p>)#', 'callback_func', $content);
function callback_func($matches)
{
  static $count = 0;
  $ret = $matches[1];
  if (++$count == 2)
    $ret .= "<p> Additional paragraph</p>";
  return $ret;
}

请注意,这个解决方案不是可重入的,它只是一个概念。

函数可以帮助str_replace()

http://php.net/manual/es/function.str-replace.php

<? str_replace('<p>This is the second paragraph</p>','<p>This is the second paragraph</p> hello world', $content);?>