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

Reg*_*dit 1 php regex

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

$content = "
<p>This is the first paragraph</p>
<p>This is the second paragraph</p>
<p>This is the third paragraph</p>";
Run Code Online (Sandbox Code Playgroud)

给定上面的一串html内容,我需要在第N段标记之后插入.

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

bea*_*022 7

您可以使用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);
Run Code Online (Sandbox Code Playgroud)

这将创建$content_table值:

Array ( [0] => [1] => This is the first paragraph
[2] => This is the second paragraph
[3] => This is the third paragraph
) 
Run Code Online (Sandbox Code Playgroud)

现在你可以改变你想要的任何东西,$content_table[2]用于第2段.例如你可以这样做:

$content_table[2] .= "hello world!";
Run Code Online (Sandbox Code Playgroud)

当你完成后,再次将表内爆为字符串:

$content = implode($content_table, "<p>");
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您确定字符串的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;
}
Run Code Online (Sandbox Code Playgroud)

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