Friday, 3 June 2016

PHP- DISPLAY CERTAIN AMOUNT OF WORDS FROM STRING/VARIABLE

If you want to display a specific amount of characters from a string, you can use the PHP built-in function substr, but from what I’m aware, there isn’t a PHP built-in function that behaves similarly for “words”. Essentially, we’re trying to create a sentence teaser.
So, for example, I have the following sentence…
We are BrightCherry web design, and we’re going to show you how to write a function to crop a string by a certain amount of words.
That sentence has 26 words, but what if we only want to show the first 10 words from that sentence?
//first 10 words from sentence
We are BrightCherry web design, and we’re going to show
And what if we want to take it one step further by calling the rest of the string, after the first 10 words…
//Words after the first 10 from the sentence
you how to write a function to crop a string by a certain amount of words.
Here are the functions I personally use…

The code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
// sentence teaser
// this function will cut the string by how many words you want
function word_teaser($string, $count){
  $original_string = $string;
  $words = explode(' ', $original_string);
 
  if (count($words) > $count){
   $words = array_slice($words, 0, $count);
   $string = implode(' ', $words);
  }
 
  return $string;
}
 
// sentence reveal teaser
// this function will get the remaining words
function word_teaser_end($string, $count){
 $words = explode(' ', $string);
 $words = array_slice($words, $count);
 $string = implode(' ', $words);
  return $string;
}
?>

The example- sentence teaser

1
2
3
4
5
6
7
$string = "We are BrightCherry web design, and we're going to show you how to write a function to crop a string  by a certain amount of words."
 
//this will echo the first 10 words of the string
echo word_teaser($string, 10);
 
//result
We are BrightCherry web design, and we're going to show

The example- sentence teaser end

1
2
3
4
5
6
7
$string = "We are BrightCherry web design, and we're going to show you how to write a function to crop a string by a certain amount of words."
 
//this will echo the words after the first 10 words
echo word_teaser_end($string, 10);
 
//result
you how to write a function to crop a string by a certain amount of words.
Obviously you can adjust the “10” to whatever integer you want.
And that’s it! I hope that has helped someone out.

0 comments:

Post a Comment