将内容放在没有图像的段落之间

Deb*_*Das 6 html php

我使用以下代码在我的内容中放置一些广告代码.

<?php
$content = apply_filters('the_content', $post->post_content);
$content = explode (' ', $content);
$halfway_mark = ceil(count($content) / 2);
$first_half_content = implode(' ', array_slice($content, 0, $halfway_mark));
$second_half_content = implode(' ', array_slice($content, $halfway_mark));
echo $first_half_content.'...';
echo ' YOUR ADS CODE';
echo $second_half_content;
?>
Run Code Online (Sandbox Code Playgroud)

我如何修改它,以便包含广告代码的2段(顶部和底部)不应该是具有图像的段落.如果顶部或底部段落有图像,则尝试接下来的2段.

示例:右侧的正确实施.

在此输入图像描述

Peb*_*bbl 3

preg_replace 版本

\n

此代码逐步执行每个段落,忽略包含图像标签的段落。对于没有图像的每个段落,该$pcount变量都会递增,但如果遇到图像,$pcount则会重置为零。一旦$pcount到达将达到两个点,广告标记就会插入到该段落之前。这应该将广告标记留在两个安全段落之间。然后广告标记变量被取消,因此仅插入一则广告。

\n

以下代码仅用于设置,可以进行修改以以不同的方式分割内容,您还可以修改使用 \xe2\x80\x94 的正则表达式,以防您使用双 BR 或其他内容来分隔段落。

\n
/// set our advert content\n$advert = '<marquee>BUY THIS STUFF!!</marquee>' . "\\n\\n";\n/// calculate mid point\n$mpoint = floor(strlen($content) / 2);\n/// modify back to the start of a paragraph\n$mpoint = strripos($content, '<p', -$mpoint);\n/// split html so we only work on second half\n$first  = substr($content, 0, $mpoint);\n$second = substr($content, $mpoint);\n$pcount = 0;\n$regexp = '/<p>.+?<\\/p>/si';\n
Run Code Online (Sandbox Code Playgroud)\n

其余的是运行替换的大部分代码。可以对其进行修改以插入多个广告,或支持更多涉及的图像检查。

\n
$content = $first . preg_replace_callback($regexp, function($matches){\n  global $pcount, $advert;\n  if ( !$advert ) {\n    $return = $matches[0];\n  }\n  else if ( stripos($matches[0], '<img ') !== FALSE ) {\n    $return = $matches[0];\n    $pcount = 0;\n  }\n  else if ( $pcount === 1 ) {\n    $return = $advert . $matches[0];\n    $advert = '';\n  }\n  else {\n    $return = $matches[0];\n    $pcount++;\n  }\n  return $return;\n}, $second);\n
Run Code Online (Sandbox Code Playgroud)\n

执行此代码后,$content变量将包含增强的 HTML。

\n
\n

5.3 之前的 PHP 版本

\n

由于您选择的测试区域不支持 PHP 5.3,因此不支持匿名函数,因此您需要使用稍作修改且不太简洁的版本;它使用命名函数来代替。

\n

另外,为了支持实际上可能不会在后半部分为广告留下空间的内容,我修改了 ,$mpoint以便计算为从末尾开始的 80%。这将产生包括更多内容的效果$second,但也意味着您的广告通常会在标记中放置在更高的位置。该代码没有实施任何后备,因为您的问题没有提到失败时应该发生什么。

\n
$advert = '<marquee>BUY THIS STUFF!!</marquee>' . "\\n\\n";\n$mpoint = floor(strlen($content) * 0.8);\n$mpoint = strripos($content, '<p', -$mpoint);\n$first  = substr($content, 0, $mpoint);\n$second = substr($content, $mpoint);\n$pcount = 0;\n$regexp = '/<p>.+?<\\/p>/si';\n\nfunction replacement_callback($matches){\n  global $pcount, $advert;\n  if ( !$advert ) {\n    $return = $matches[0];\n  }\n  else if ( stripos($matches[0], '<img ') !== FALSE ) {\n    $return = $matches[0];\n    $pcount = 0;\n  }\n  else if ( $pcount === 1 ) {\n    $return = $advert . $matches[0];\n    $advert = '';\n  }\n  else {\n    $return = $matches[0];\n    $pcount++;\n  }\n  return $return;\n}\n\necho $first . preg_replace_callback($regexp, 'replacement_callback', $second);\n
Run Code Online (Sandbox Code Playgroud)\n