Changing code from regex

I have the following 2 sets of code (WordPress) using regex, but I was told that it’s a bad practice.
I am using it in 2 ways:

  1. To ake out the blockquote and images from the post and just display the text.
  2. To essentially do the opposite and display just the images.

Looking to write it in the proper more acceptable/cross browser form.

Read More

html (display text):

<?php
$content = preg_replace('/<blockquote>(.*?)</blockquote>/', '', get_the_content());
$content = preg_replace('/(<img [^>]*>)/', '', $content);
$content = wpautop($content); // Add paragraph-tags
$content = str_replace('<p></p>', '', $content); // remove empty paragraphs
echo $content;
?>  

html (display images):

<?php
preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
for( $i=0; isset($images[1]) && $i < count($images[1]); $i++ ) {
    if ($i == end(array_keys($images[1]))) {
        echo sprintf('<div id="last-img">%s</div>', $images[1][$i]);
        continue;
    }
    echo $images[1][$i];
}
?>

Related posts

Leave a Reply

1 comment

  1. You can use the answer from here: Strip Tags and everything in between

    The point is to use a parser, rather than roll-your-own regex that might be buggy.

    $content = get_the_content();
    $content = wpautop($content);
    
    $doc = new DOMDocument();
    $doc->loadHTML(get_the_content(), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    $xpath = new DOMXPath($doc);
    
    foreach ($xpath->query('//blockquote') as $node) {
        $node->parentNode->removeChild($node);
    }
    
    foreach ($xpath->query('//img') as $node) {
        $node->parentNode->removeChild($node);
    }
    
    foreach( $xpath->query('//p[not(node())]') as $node ) {
        $node->parentNode->removeChild($node);
    }
    
    $content = $doc->saveHTML($doc);
    

    You may find that php DOMDocument has wrapped your html fragment in <html> tags, in which case look at How to saveHTML of DOMDocument without HTML wrapper?

    The part that removes empty p tags is from Remove empty tags from a XML with PHP