改变Imploding和Exploding

时间:2017-11-19 05:50:38

标签: php

此代码在内容中添加广告。我想改变输出。我添加了新的细节。我尝试过,但我无法解决问题。

add_filter( 'the_content', 'ads_paragraphs');
function ads_paragraphs( $content ) {

    $adsbeforeparagraph = array(1,3,5);

    global $post;

     $ad = 'ADS CODE';

    $content_expl = explode("<p>", $content);
    for ($i = 0; $i <count($content_expl); $i++ ) {
        if (in_array($i, $adsbeforeparagraph)){
            $content_expl[$i] = $ad . $content_expl[$i];
            }
    } 

     return implode("<p>", $content_expl);
    }

输入在这里:

<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>

输出在这里:

<p>ADS CODEtext text text</p>
<p>text text text</p>
<p>ADS CODEtext text text</p>
<p>text text text</p>
<p>ADS CODEtext text text</p>
<p>text text text</p>

我想要这个输出:

ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>

2 个答案:

答案 0 :(得分:1)

像这样使用

       $adsbeforeparagraph = array(1,3,5);

   global $post;

    $ad = 'ADS CODE';
    $content='<p>text text text </p>
                <p>text text text</p>
                <p>text text text </p>
                <p>text text text </p>
                <p>text text text </p>
                <p>text text text </p>';
    $content_expl = explode("<p>", $content);
    for ($i = 1; $i <count($content_expl); $i++ ) {     
        if (in_array($i, $adsbeforeparagraph)){
            $content_expl[$i] ='ADS CODE <p>'.$content_expl[$i].'<p>';
        }
    }
    print_r(implode(" ", $content_expl));

检查一下,我已经检查了这个。它有效......

答案 1 :(得分:1)

这是你在找什么?

我使用in_array来确定当前行是否应该有广告。
请注意,我从您的值中减去1,因为正常数组从0开始计数 如果你必须有1,3,5我可以解决这个问题。

$input= "<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>";

$arr =explode(PHP_EOL, $input);

 $adsbeforeparagraph = array(0,2,4); // subtracted 1 to suit normal array numbering
 $ad = 'ADS CODE';

Foreach($arr as $key => $line){
    If(in_array($key, $adsbeforeparagraph)){ // is this a line that should have Ads?
        Echo $ad . $line . "\n";
    }else{
        Echo $line . "\n";
    }
}

输出:

ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>

https://3v4l.org/8DVua