Skip to main content

How can I truncate a string in PHP?



How can I truncate a string after 20 words in PHP?





Source: Tips4all

Comments

  1. function limit_text($text, $limit) {
    if (strlen($text) > $limit) {
    $words = str_word_count($text, 2);
    $pos = array_keys($words);
    $text = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
    }

    echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5);


    Outputs:

    Hello here is a long ...

    ReplyDelete
  2. change the "2" to 19 to get first 20 words. This one gets the first 3 words:

    function first3words($s) {
    return preg_replace('/((\w+\W*){2}(\w+))(.*)/', '${1}', $s);
    }

    var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world"
    var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world"
    var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world"
    var_dump(first3words("hello yes world")); # => "hello yes world"
    var_dump(first3words("hello yes world.")); # => "hello yes world"
    var_dump(first3words("hello yes")); # => "hello yes"
    var_dump(first3words("hello")); # => "hello"
    var_dump(first3words("a")); # => "a"
    var_dump(first3words("")); # => ""

    ReplyDelete
  3. This looks pretty good to me:


    A common problem when creating dynamic
    web pages (where content is sourced
    from a database, content management
    system or external source such as an
    RSS feed) is that the input text can
    be too long and cause the page layout
    to 'break'.

    One solution is to truncate the text
    so that it fits on the page. This
    sounds simple, but often the results
    aren't as expected due to words and
    sentences being cut off at
    inappropriate points.

    ReplyDelete
  4. Split the string (into an array) by <space>, and then take the first 20 elements of that array.

    ReplyDelete
  5. Try regex.

    You need something that would match 20 words (or 20 word boundaries).

    So (my regex is terrible so correct me if this isn't accurate):

    /(\w+\b){20}/


    And here are some examples of regex in php.

    ReplyDelete
  6. Something like this could probably do the trick:

    <?php
    $words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));

    ReplyDelete
  7. use PHP tokenizer function strtok() in a loop.

    $token = strtok($string, " "); // we assume that words are separated by sapce or tab
    $i = 0;
    $first20Words = '';
    while ($token !== false && $i < 20) {
    $first20Words .= $token;
    $token = strtok(" ");
    $i++;
    }
    echo $first20Words;

    ReplyDelete
  8. use explode() .

    Example from the docs.

    // Example 1
    $pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
    $pieces = explode(" ", $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2


    note that explode has a limit function. So you could do something like

    $message = implode(" ", explode(" ", $long_message, 20));

    ReplyDelete
  9. based on 動靜能量's answer:

    function truncate_words($string,$words=20) {
    return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
    }


    or

    function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
    $new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
    if($new != $string){
    return $new.$ellipsis;
    }else{
    return $string;
    }

    }

    ReplyDelete
  10. Truncates to nearest preceding space of target character.

    <?php

    $str = "this is a string that is just some text for you to test with";

    print(truncateString($str, 20, true) . "\n");
    print(truncateString($str, 22, true) . "\n");
    print(truncateString($str, 24, true) . "\n");
    print(truncateString($str, 26, true, " :)") . "\n");
    print(truncateString($str, 28, true, "--") . "\n");

    function truncateString($str, $chars, $to_space, $replacement="...") {
    if($chars > strlen($str)) return $str;

    $str = substr($str, 0, $chars);

    $space_pos = strrpos($str, " ");
    if($to_space && $space_pos >= 0) {
    $str = substr($str, 0, strrpos($str, " "));
    }

    return($str . $replacement);
    }

    ?>

    /* OUTPUT
    this is a string...
    this is a string that...
    this is a string that...
    this is a string that is :)
    this is a string that is--
    */


    You can see a demo here.

    ReplyDelete
  11. what about

    chunk_split($str,20);


    Entry in the PHP Manual

    ReplyDelete
  12. Here is what I have implemented.

    function summaryMode($text, $limit, $link) {
    if (str_word_count($text, 0) > $limit) {
    $numwords = str_word_count($text, 2);
    $pos = array_keys($numwords);
    $text = substr($text, 0, $pos[$limit]).'... <a href="'.$link.'">Read More</a>';
    }
    return $text;
    }


    As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.

    I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.

    ReplyDelete
  13. Here's one I use:

    $truncate = function( $str, $length ) {
    if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
    $str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
    return htmlspecialchars($str[0]) . '&hellip;';
    } else {
    return htmlspecialchars($str);
    }
    };
    return $truncate( $myStr, 50 );

    ReplyDelete
  14. Its not my own creation, its a modification of previous posts. credits goes to karim79...!!! thanks yaar...

    function limit_text($text, $limit) {
    $strings = $text;
    if (strlen($text) > $limit) {
    $words = str_word_count($text, 2);
    $pos = array_keys($words);
    if(sizeof($pos) >$limit)
    {
    $text = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
    }
    return $text;
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?

Java Urban Myths

Along the line of C++ Urban Myths and Perl Myths : What are the Java Urban Myths? That is, the ideas and conceptions about Java that are common but have no actual roots in reality . As a Java programmer, what ideas held by your fellow Java programmers have you had to disprove so often that you've come to believe they all learned at the feet of the same drunk old story-teller? Ideally, you would express these myths in a single sentence, and include an explanation of why they are false.

CCNA 1 Final Exam 2011 latest (hot hot hot)

  Hi! I have been posted content of ccna1 final exam (latest and only question.) I will post the answer and insert image on sunday. If you care, please subscribe your email an become a first person have full test content. Subcribe now  Some question  have not content because this question have images content. So that can you wait for me? SUNDAY 1. A user sees the command prompt: Router(config-if)# . What task can be performed at this mode? Reload the device. Perform basic tests. Configure individual interfaces. Configure individual terminal lines. 2. Refer to the exhibit. Host A attempts to establish a TCP/IP session with host C. During this attempt, a frame was captured with the source MAC address 0050.7320.D632 and the destination MAC address 0030.8517.44C4. The packet inside the captured frame has an IP source address 192.168.7.5, and the destination IP address is 192.168.219.24. At which point in the network was this packet captured? leaving host A leaving ATL leaving...