PHP:在body标签后面注入iframe

时间:2010-02-07 07:01:08

标签: html regex php4

我想在body标签的开头正下方放置一个iframe。这有一些问题,因为body标签可以有各种属性和奇怪的空白。我的猜测是这将需要正则表达式才能正确完成。

编辑:此解决方案必须与php 4&表现是我​​的担忧。这是http://drupal.org/node/586210#comment-2567398

3 个答案:

答案 0 :(得分:5)

您可以使用DOMDocument和朋友。假设您有一个包含现有HTML文档的变量html作为字符串,基本代码为:

$doc = new DOMDocument();
$doc->loadHTML(html);
$body = $doc->getElementsByTagName('body')->item(0);
$iframe = $doc->createElement('iframe');
$body->insertBefore($iframe, $body->firstChild);

要检索修改后的HTML文本,请使用

$html = $doc->saveHTML();

编辑:对于PHP4,您可以尝试DOM XML

答案 1 :(得分:4)

PHP 4和PHP 5都应该对preg_split()

感到满意
/* split the string contained in $html in three parts: 
 * everything before the <body> tag
 * the body tag with any attributes in it
 * everything following the body tag
 */
$matches = preg_split('/(<body.*?>)/i', $html, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 

/* assemble the HTML output back with the iframe code in it */
$injectedHTML = $matches[0] . $matches[1] . $iframeCode . $matches[2];

答案 2 :(得分:0)

使用正则表达式会带来性能问题......这就是我想要的

<?php
$html = file_get_contents('http://www.yahoo.com/');
$start = stripos($html, '<body');
$end = stripos($html, '>', $start);
$body = substr_replace($html, '<IFRAME INSERT>', $end+1, 0);
echo htmlentities($body);
?>

思想?