Freelancer's Playground! Learn Programming, The Freelancer's Way

3Feb/105

Get Only n Words From String

Here's the code:

function trim_word( $words, $howmany = 1){
	$x = explode(" ", $words);
	if(count( $x) <=$howmany ){
		return $words;
	} else {
		return implode(" ", array_slice( $x, 0, $howmany));
	}
}

Here's the output:

$words = "this is string that is long enough that I want to trim it.";

echo trim_word($words, 10) . "\n";
//this will echo: this is string that is long enough that I want

UPDATE:

  1. 2010-02-05 15:03:25 - Fixing $howmany usage. Sorry, for the inconvenience:D
Filed under: snippet Leave a comment
  • sepertinya itu variabel $howmany di parameter kok nganggur ya? :D apakah itu parameter untuk mengatur berapa kata yang ingin ditampilkan? jadi gant semua angka 10 di fungsi itu dengan variabel $howmany

    CMIIMW
  • Yup, anda benar:D
  • Ternyata kodenya ada sedikit bugs.. saya coba ganti parameter angka 10 dengan angka lebih tinggi hasilnya tetep 10 words aja bro..

    Gimana solusinya?
  • Solusinya, seperti yang ditulis @essajiwa. Ganti semua angka 10 dengan variable $howmany. Anyway, posting juga udah di update dengan script yang benar. Monggo di CP atau di test lagi.
  • Let's me test it and I hope it's worked
blog comments powered by Disqus