3v4l.org

run code in 300+ PHP versions simultaneously
<?php $post_content = "<p>There are 14 more days until our <a href=\"/somepage.html\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"join us\">holiday special</a> so come join us!</p>"; $dom = new DOMDocument(); $dom->loadHTML($post_content); $xpath = new DOMXPath($dom); $all_text_nodes = $xpath->query("//text()"); $words_left = 9; // reduced for this text to cut off at "holiday" foreach( $all_text_nodes as $text_node) { $text = $text_node->textContent; $words = explode(" ", $text); // TODO: maybe preg_split on /\s/ to support more whitespace types $word_count = count($words); if( $word_count < $words_left) { $words_left -= $word_count; continue; } // reached the threshold $words_that_fit = implode(" ", array_slice($words, 0, $words_left)); // If the above TODO is implemented, this will need to be adjusted to keep the specific whitespace characters $text_node->textContent = $words_that_fit; $remove_after = $text_node; while( $remove_after->parentNode) { while( $remove_after->nextSibling) { $remove_after->parentNode->removeChild($remove_after->nextSibling); } $remove_after = $remove_after->parentNode; } break; } $output = substr($dom->saveHTML($dom->getElementsByTagName("body")->item(0)), strlen("<body>"), -strlen("</body>")); echo $output;

preferences:
22.48 ms | 407 KiB | 5 Q