开发者

How to replace ##th match in a string in php?

So here comes the problem: I want to paste an advertisement after a specified ##th paragraph.

Let me show:

<p><img src="an/images/pic.jpg" /></p>
<p>Intro text</p>
<p>A paragraph</p>
<p>Another paragraph</p>

I want to paste the advertisement below the second paragraph. The final code should be like that:

<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>

I tried some regexp but i don't get it. Ladies and Gentlemen please help me.


Taking RegEx match open tags except XHTML self-contained tags into consideration you might want to use a DOM/HTML parser for this.

<?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>';
}

prints

<!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>


<p><img src="an/images/pic.jpg" /></p>

Don't forget to put an " at the end.

Egyébként Jó napot! :)


The following code should echo the advert after every fifth paragraph tag and after the the second paragraph. It should give you enough to modify and get it working.

It use two key functions:

  • explode() man page
  • implode() man page

The code:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜