Extract a fixed number of chars from an array, just full words

Hey there,
I have a custom text inside a variable:

$myvar = 'this is my custom text, it is a very long text so be patiente, take care!";

I need to display lets say the first 100 chars from $myvar, but i need full words.
For example:
this is my custom text, it is a ver… (i don’t want to cut words when i extract)

How can i do this?

Thank you!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

There are heaps of ways, but try this:

$shortVersion = substr($myvar, 0, 100);
if(strlen($myvar)>100 && preg_match('`\w`', $myvar{100}))
    $shortVersion = preg_replace('`\w+$`', '', $shortVersion);

That’s probably your path of least resistance.

Solution 2

There are a number of examples of this in the user comments on substr() function

One of the simpler ones is:

function wrapTrunc($str, $len) {
  return substr(($str=wordwrap($myvar,$len,'$$')),0,strpos($str,'$$'));
}

A major disadvantage of this wordwrap-based approach is you waste time and memory wrapping the whole string, even though you only need to keep the first $len chars.

Here’s a regex-based solution I just whipped up that I’m a little more comfortable with:

<?php
$myvar = 'this is my custom text, it is a very long text so be patiente, take care!';
var_dump(trunc($myvar, 50));
function trunc($str, $len = 50) {
  return preg_replace("/^(.{1,$len}\S)\b.*/", '$1', $str);
}

Sample output:

$ php test.php
string(49) "this is my custom text, it is a very long text so"

Solution 3

Well… Since we’re putting code in, my 2 cents:

<?php
function noWordCut($str, $len, $before=true, $add=' ...', $punctuation=array(' ',',','.','!','?',';')){
    if(!isset($str[$len]))return $str;
    if(in_array($str[$len], $punctuation))return substr($str, 0, $len).$add;
    $dir=($before)?-1:1;
    for(;$len+=$dir;)
        if(in_array($str[$len], $punctuation))
            return substr($str, 0, $len).$add;
    return $str;// one big chunk of word?
}
?>

Solution 4

Guess what. There is a built-in PHP function for that 🙂

print wordwrap($text, 100);

Ooops, for cutting of the first line you can use:

$first = strtok(wordwrap($text, 100), "\n");

Solution 5

Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:

  • script_tags() PHP function to remove the unnecessary HTML and PHP
    tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
  • explode() to split the $string into an array
  • array_splice() to specify the number of words and where it’ll start
    from. It’ll be controlled by vallues assigned to our $start and $limit variables.
  • and finally, implode() to join the array elements into your truncated
    string..

    function truncateString($string, $start, $limit){
        $stripped_string =strip_tags($string); // if there are HTML or PHP tags
        $string_array =explode(' ',$stripped_string);
        $truncated_array = array_splice($string_array,$start,$limit);
        $truncated_string=implode(' ',$truncated_array);
    
        return $truncated_string;
    }
    

It’s that simple..

I hope this was helpful.

Solution 6

Here’s a bad example that probably wastes lots of processing time and memory:

<?php
    $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin congue, quam nec tincidunt congue, massa ipsum sodales tellus, in rhoncus sem quam quis ante. Nam condimentum pellentesque libero at blandit.";
    $length = 100;
    $words = explode(' ', $text);
    for ($x=0; $x <= count($words); $x++) {
        $output = implode(' ', array_slice($words, 0, $x));
        if (strlen($output) >= $length) {
            echo $output . '...';
            break;
        }
    }
?>

Why? Because I can.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply