Shaikh Sonny Aman’s Blog

previously www.mailtoaman.com

Snip first words from first n charecters using php

Posted on | September 9, 2008 |

Problem: You are writing a blogging software. Where on the first page you like to show the lates posts in a list but not their full content, only say first 200 letters. Porblem raises  when the last word is spans out of the 200 letter limit.

For example, say, 198th letter is ‘H’ which is the start of the word ‘Home’. So, if you take only first 200 letters, the text will endup with ‘Hom’, certainly thats unwanted.

What to do?

Ans:

One solution can be like this:

/**
*   @param text The Text from where to snip
*   @param n     The limit, 200 in the above example
*/

function getWordsInN($text,$n){
return substr($text = substr($text,0,$n)
,0,
strrpos($text,‘ ‘)
);
}

Comments

2 Responses to “Snip first words from first n charecters using php”

  1. hasin hayder
    September 16th, 2008 @ 3:25 am

    nice one. but i would suggest you to change the name of this function to a more meaningful one - like “truncate”

    :)

  2. admin
    September 16th, 2008 @ 10:35 am

    yea !!
    Thank you Hasin bhai for suggesting a meaningful name and visting me :)

    best wishes.

Leave a Reply