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の場合、DOMXMLを試すことができます

于 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 に答える