Divide text string into sections (separate divs) of 500 characters (or any other # of characters) using PHP? -


what best method taking text string (from mysql database, wordpress post or page) , dividing text sections of 500 characters (or other number of characters), , outputting each 500-character section wrapped in own div container?

being new php, i'm not sure how go segmenting content based on character count. character count using:

<?php $content = get_the_content(); //wordpress function post content string. echo strlen($content); ?> 

but far knowledge goes. can me out challenge?

let's requesting page of content wordpress database, , 5,000 characters long. goal output 10 divs or spans each contained 500 characters.

thank in advance assistance.

php offers function that, called 'str_split()'. can use this:

<?php $content = get_the_content(); $chunks = str_split($content, 500);  //printing each chunk in div foreach($chunks $chunk_content) {     echo "<div>";     echo $chunk_content;     echo "</div>"; } ?> 

more info str_split: http://www.php.net/manual/en/function.str-split.php

edit: if words should not cut in middle, use function instead:

<?php $content = get_the_content(); $strings = wordwrap($content, 500, "{break}"); //put {break} every 500 characters $chunks = explode("{break}", $strings); //put each segment separated {break} array field  //printing each chunk in div foreach($chunks $chunk_content) {     echo "<div>";     echo $chunk_content;     echo "</div>"; } ?> 

if want save memory, can combine these functions this:

<?php foreach(explode("{break}", wordwrap(get_the_content(), 500, "{break}")) $chunk) {     echo "<div>" . $chunk . "</div>\n"; //the \n creates new line } ?> 

for more information concerning wordwrap see http://www.php.net/manual/en/function.wordwrap.php


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -