所以这就出现了问题: 我想在指定的## th段后粘贴广告。
让我说明一下:
<p><img src="an/images/pic.jpg" /></p>
<p>Intro text</p>
<p>A paragraph</p>
<p>Another paragraph</p>
我想在第二段下面粘贴广告。最终的代码应该是这样的:
<p><img src="an/images/pic.jpg /></p>
<p>Intro text</p>
<div>Yepp, let's make money</div>
<p>A paragraph</p>
<p>Another paragraph</p>
我尝试了一些正则表达式,但我没有得到它。女士们,先生们,请帮助我。
答案 0 :(得分:1)
考虑RegEx match open tags except XHTML self-contained tags,您可能希望使用DOM / HTML解析器。
<?php
$doc = new DOMDocument;
$doc->loadhtml( getHTML() );
$xpath = new DOMXPath($doc);
$ns = $xpath->query( '/html/body/p[2]' );
if ( 0 < $ns->length ) {
$parent = $ns->item(0)->parentNode;
$nextSibling = $ns->item(0)->nextSibling;
$p = $doc->createElement('p', 'Hi, this is Scott coming to you from another place and time');
$parent->insertBefore($p, $nextSibling);
}
echo $doc->savehtml();
function getHTML() {
return '<html><head><title>...</title><body>
<p><img src="an/images/pic.jpg" /></p>
<p>Intro text</p>
<p>A paragraph</p>
<p>Another paragraph</p>
</body></html>';
}
打印
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><title>...</title></head><body>
<p><img src="an/images/pic.jpg"></p>
<p>Intro text</p><p>Hi, this is Scott coming to you from another place and time</p>
<p>A paragraph</p>
<p>Another paragraph</p>
</body></html>
答案 1 :(得分:0)
<p><img src="an/images/pic.jpg" /></p>
不要忘记“最后”。
EgyébkéntJónapot! :)
答案 2 :(得分:0)
以下代码应在每个第五段标记之后和第二段之后回显广告。它应该足以让你修改并使其正常工作。
它使用两个关键功能:
代码:
$output = array();
$input = explode('<p>', $input);
foreach($input as $key => $line) {
$output[] = '<p>' . $line;
// every fifth paragraph
if(($key % 5) === 0) {
$output[] = '<div>Yepp, let\'s make money</div>';
}
// second paragraph
if($key === 1) {
$output[] = '<div>Yepp, let\'s make money</div>';
}
}
echo implode('', $output);