2

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

编辑:此解决方案必须与 php 4 一起使用,性能是我关心的问题。这是为了这个http://drupal.org/node/586210#comment-2567398

4

3 回答 3

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

于 2010-02-07T07:17:02.510 回答
3

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];
于 2010-02-07T08:02:13.527 回答
1

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

<?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);
?>

想法?

于 2010-02-13T21:05:12.807 回答