Viewed   85 times

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

 Answers

1
function limit_text($text, $limit) {
    if (str_word_count($text, 0) > $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 that will be truncated by the', 5);

Outputs:

Hello here is a long ...
Monday, December 5, 2022
4

You need a Ajax call to pass the JS value into php variable

JS Code will be (your js file)

var jsString="hello";
$.ajax({
    url: "ajax.php",
    type: "post",
    data: jsString
});

And in ajax.php (your php file) code will be

$phpString = $_POST['data'];     // assign hello to phpString 
Thursday, November 10, 2022
 
2

alert('my name is: <?php echo $man; ?>' );

Friday, August 19, 2022
 
1

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";
  • Tested here

And you can also use a plugin:

  • jQuery Expander Plugin

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);
Saturday, December 10, 2022
 
dkinzer
 
3

You can pass the limit as the third parameter of explode that will do the job.

$split = explode('-', 'orange-yellow-red',2);
echo $split[1]; //output yellow-red
Friday, September 23, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :