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

StackOverflow https://stackoverflow.com/questions/18264413

Question

What is the best method for taking a text string (from a mysql database, like a wordpress post or page) and dividing the text into sections of 500 characters (or any other number of characters), and then outputting each 500-character section wrapped in its own div container?

Being new to PHP, I'm not sure how to go about segmenting the content based on character count. We could get the character count using:

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

But that is as far as my knowledge goes. Can anyone help me out with this challenge?

Let's say I was requesting a page of content from the wordpress database, and it was 5,000 characters long. The goal would be to output 10 divs or spans that each contained 500 characters.

THANK YOU in advance for any assistance.

Was it helpful?

Solution

PHP offers a function for that, it is called 'str_split()'. You can use it like this:

<?php
$content = get_the_content();
$chunks = str_split($content, 500);

//Printing each chunk in a div
foreach($chunks as $chunk_content) {
    echo "<div>";
    echo $chunk_content;
    echo "</div>";
}
?>

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

EDIT: If words should not get cut in the middle, use this function instead:

<?php
$content = get_the_content();
$strings = wordwrap($content, 500, "{BREAK}"); //Put a {BREAK} every 500 characters
$chunks = explode("{BREAK}", $strings); //Put each segment separated by {BREAK} into an array field

//Printing each chunk in a div
foreach($chunks as $chunk_content) {
    echo "<div>";
    echo $chunk_content;
    echo "</div>";
}
?>

If you want to save some memory, you can combine these functions like this:

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top