Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

php question

  • 27-02-2006 10:22AM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 Posts: 2,203 ✭✭✭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, Registered Users 2 Posts: 648 ✭✭✭ChicoMendez


    Thanks alot that was perfect!


Advertisement