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;
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
<p>There are 14 more days until our <a href="/somepage.html" target="_blank" rel="noreferrer noopener" aria-label="join us">holiday</a></p>

preferences:
80.92 ms | 407 KiB | 5 Q