【发布时间】:2018-09-28 20:43:24
【问题描述】:
我需要这样间隔插入一个广告代码:
-
$insert_every_paragraphs是一个变量,指示段落在文本中出现的频率。例如 10 个。 -
$minimum_paragraph_count用于查看文本是否足够长以容纳任何广告,另外第一个广告应该出现在这么多段落之后(然后它应该重复 #1 中的间隔)。 4,例如。 - 广告代码的工作方式如下:x100、x101、x102、x103 等。用户可以设置有多少可以添加。它们像
[cms_ad:x100]一样呈现,PHP 稍后替换它们(这部分工作正常)。 - 代码在 #3 结束时应该停止添加广告。也就是说,即使它有足够的段落来继续添加广告,它也应该在达到 x104 时停止(在本例中)。
所以在这个例子中,它会这样工作:在 4 个段落之后,插入 x100。然后,每 10 个段落插入另一个,直到插入 x103。不要插入 x104,即使有 100 个段落。而且,如果没有至少 34 个段落,x103 将永远不会出现。
到目前为止,我所拥有的是:
$paragraph_end = '</p>';
$insert_every_paragraphs = 10;
$minimum_paragraph_count = 4;
$embed_prefix = 'x';
$start_embed_id = 'x100';
$start_embed_count = intval( str_replace( $embed_prefix, '', $start_embed_id ) ); // ex 100
$end_embed_id = 'x103';
$end_embed_count = intval( str_replace( $embed_prefix, '', $end_embed_id ) ); // ex 104
$paragraph_positions = array();
$last_position = -1;
while ( stripos( $content, $paragraph_end, $last_position + 1 ) !== false ) {
// Get the position of the end of the next $paragraph_end.
$last_position = stripos( $content, $paragraph_end, $last_position + 1 ) + 3;
$paragraph_positions[] = $last_position;
}
// If the total number of paragraphs is bigger than the minimum number of paragraphs
if ( count( $paragraph_positions ) >= $minimum_paragraph_count ) {
// How many ads have been added?
$n = $start_embed_count;
// Store the position of the last insertion.
$previous_position = $start_embed_count;
$i = 0;
while ( $i < count( $paragraph_positions ) && $n <= $end_embed_count ) {
if ( 0 === ( $i + 1 ) % $insert_every_paragraphs && isset( $paragraph_positions[ $i ] ) ) {
$shortcode = "\n" . '[cms_ad:' . $embed_prefix . (int) $n . ']' . "\n";
$position = $paragraph_positions[ $i ] + 1;
if ( $position > $previous_position ) {
$content = substr_replace( $content, $shortcode, $paragraph_positions[ $i ] + 1, 0 );
// Increase the saved last position.
$previous_position = $position;
// Increment number of shortcodes added to the post.
$n++;
}
// Increase the position of later shortcodes by the length of the current shortcode.
foreach ( $paragraph_positions as $j => $pp ) {
if ( $j > $i ) {
$paragraph_positions[ $j ] = $pp + strlen( $shortcode );
}
}
}
$i++;
}
}
当数字是 4 和 6 而不是 4 和 10 时,我认为这可以正常工作,但是当我开始调整值时,错误变得清晰起来。它目前每10段插入一个广告,当然它不会在第四段之后插入一个广告。
当然,我不反对为此使用explode 或其他方法,但这是让我走得最远的原因。
【问题讨论】:
-
旁注: 在您发布的代码中,
;缺少$start_embed_id = 'x100' -
“而且第一个广告应该出现在这么多段落之后”是主要问题,对吧?
-
@Jeff 谢谢,我太急于清理东西了。但是,是的,主要问题是这可能段落之后的第一个广告。
-
那么如果第一个广告在第 4 段之后,那么第二个广告是在第 10 段之后还是第 14 段之后?
-
@Anthony 如果第一个广告在第 4 段之后,第二个将在第 14 段之后。