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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

php question

  • 27-02-2006 9: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,170 ✭✭✭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