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 (3) Add New Comment
dewacasino2024-05-02 12:29 PM

Sejak lama, judi online poker, slot, casino, dan togel terpercaya Indonesia telah menjadi daya tarik utama bagi para penggemar judi. Dengan pelbagai pilihan permainan yang menarik dan kesempatan untuk memenangkan hadiah besar, industri perjudian online terus berkembang pesat. Para pemain dapat merasakan sensasi perjudian yang mengasyikan dan memikat serta menikmati kemewahan layanan terpercaya yang sudah menjadi komponen tak terpisahkan dari kebiasaan perjudian di Indonesia.

Reply
blog del narco2024-02-08 11:43 AM

Institutions reporting to the central government likely have closer to $six trillion in foreign assets, Setser mentioned.

Reply
web,2024-02-07 4:49 AM

I really like what you guys are usually up too. This sort of clever work and exposure! Keep up the awesome works guys I've incorporated you guys to my personal blogroll.

Reply