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

时间:2012-01-22 19:14:49

标签: php regex

  

可能重复:
  How to parse and process HTML with PHP?

$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段之后说“你好世界”?

3 个答案:

答案 0 :(得分:7)

您可以使用PHP explodeimplode函数。这是一个概念:

$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>");

答案 1 :(得分: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;
}

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

答案 2 :(得分:-3)

函数可以帮助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);?>