dougou8573
dougou8573
2013-08-16 01:26

使用PHP将文本字符串分成500个字符(或任何其他字符)的部分(单独的div)?

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doujiao1180 doujiao1180 8年前

    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>
    "; //The 
     creates a new line
    }
    ?>
    

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

    点赞 评论 复制链接分享