2019-10-07 Pujan Niroula 1 Minute(s) Read

[How to] Create Snippet Without Breaking Word in PHP

img-substr long text wo breaking word 1.jpg

Hello there, I am back with new script to create snippet of long text without breaking word.

Recently I have been working on a friend's site he asked me to make create snippet of blog post just like this blog.

I created it like

<?php
//Long text to break
$long_text = "Let's use PHP Substr to break the word to create snippet of certain length of a very long text.";
$snippet = substr($long_text, 0, 50);
echo $snippet;
?>

Substr Long String Without Breaking a Word

 This script will break the text after 30 characters but he doesn't want to break word so asked me to fix it. I never thought about that but I have to create this. After some googling I found perfect method to do so.

<?php
$text = "This is long text to be broken into short snippest just like this blog but little bit advance which won't break any word. Just Check this out and keep visiting this blog for more cool tricks and tips";
$length = 10;
$max_length = 30; //Set Maxlength of last word so that a long very long single word to be broken

if(strlen($text)<=$length){
    echo substr($text, 0, $length);
} else {
    for ($i=0; $i<=$max_length; $i++) {

        if($text[$length+$i]==' ' OR $i==$max_length){

            echo substr($text, 0, $length+$i);
            break;    
        }
    }
}
?>

Furthermore, I have added $max_length variable so that if a user submit a long word it will break and create snippet. I think practically there is no word longer than 30 character.

Thanks for reading, and happy coding.

Comments (1) Add New Comment
No comments, Be first one to commment!