Home > Software engineering >  PHP: Explode/Implode content including heading tags
PHP: Explode/Implode content including heading tags

Time:12-27

I have the following:

<?php
        $content = apply_filters( 'the_content', get_the_content() );
        
        $content_table = explode("<p>", $content);

        $content_table[3] .= $spot1;
        $content_table[6] .= $spot2;
        $content_table[9] .= $spot3;
        $content_table[12] .= $spot4;
        $content_table[15] .= $spot5;

        $content2 = implode($content_table, "<p>");
        
        echo $content2;
?>

This grabs the content from the page (Wordpress) and then after each 3rd paragraph inserts a custom shortcode (ie. $spot1) - this works great, but it only applies to paragraphs. How do I also include H2 tags? Because it only applies to paragraphs I find that the $spot1 comes after the heading - but I want to include headings in the equation - so that it counts these as well.

CodePudding user response:

We can build a custom function that will act as a multi-separators explode using str_replace() and explode().

<?php

/**
 * Multi-separators explode.
 * Split a string by an array of separators.
 * PHP version >= 8.0.0 required.
 * 
 * @param Array $separators. The boundaries.
 * @param String $string. The input string.
 * 
 * @return Array Returns an array of strings created by splitting the string parameter on boundaries formed by an array of separators.
 * 
 * @see https://stackoverflow.com/a/70468985/3645650
 */
if ( ! function_exists( 'wpso70468351' ) ) {
    function wpso70468351( $separators, $string ) {
        if ( version_compare( PHP_VERSION, '8.0.0', '<' ) ) //Verify the current PHP version. Due to the use of the explode default function recently released with PHP 8.0.0.
            return;

        $buffer = str_replace( $separators, $separators[0], $string );
        return explode( $separators[0], $buffer );
    };
};

On the front-end, we can call our function to parse our content.

<?php

echo '<pre>';
print_r( wpso70468351( ['<h2>', '<p>'], get_the_content() ) );
echo '</pre>';

CodePudding user response:

// add marker to paragraphs
$content = str_replace('</p>', '</p>[marker]', $content);

// add marker to h2 tags
$content = str_replace('</h2>', '</h2>[marker]', $content);

// explode by marker
$content_table = array_map('trim', explode("[marker]", $content));
  • Related