Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

php question

Options
  • 27-02-2006 10:22am
    #1
    Registered Users Posts: 648 ✭✭✭


    Hi
    Im messing with php here for a site. What i want to do is display the first hundred characters of a certain db field if its greater than 100 character and then display ... (which i can do no probs)
    However if there is a word present at character 100 it will cut it up. how can i stop this and make sure the ... appears after a word?

    Thank you


Comments

  • Registered Users Posts: 2,157 ✭✭✭Serbian


    I put together a PHP function that should do what you are looking for. I just wrote it now and didn't really test it so you may have to tweak it a bit. It should return all the full words within the first 100 characters.

    [php]<?php
    $string = "This is a string which I want to cut at 100 characters. However, I want it to display a full word at the end and not just part of the word.";
    $cut_off_point = 100;
    $string_length = strlen($string);

    function SplitString($string, $cut_off=100) {
    if(is_numeric($cut_off)) {
    if(strlen($string)>$cut_off) {
    $words = preg_split("/\s+/", $string);
    $string = "";
    $pos = 0;
    do {
    $string .= $words[$pos]." ";
    $pos++;
    } while (strlen($string)<$cut_off);
    $string = rtrim($string, " ");
    }
    }
    return $string;
    }

    $string = SplitString($string);
    print $string."...";
    ?>
    [/php]

    Edit: There's some weirdness with the str_word_count() function - it treats numbers as white space. Swapped it for RegEx.


  • Registered Users Posts: 648 ✭✭✭ChicoMendez


    Thanks alot that was perfect!


Advertisement