How can I truncate a string after 20 words in PHP?
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
Outputs:
Hello here is a long ...
Change the number 3 to the number 20 below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3 to 20 to change the default value):
function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);
}
var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world"
var_dump(first3words("hello yes world")); # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes")); # => "hello yes"
var_dump(first3words("hello")); # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words("")); # => ""
To Nearest Space
Truncates to nearest preceding space of target character. Demo
$str The string to be truncated
$chars The amount of characters to be stripped, can be overridden by $to_space
$to_space boolean for whether or not to truncate from space near $chars limit
Function
function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;
$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));
return($str . $replacement);
}
Sample
<?php
$str = "this is a string that is just some text for you to test with";
print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");
?>
Output
this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--
use explode() .
Example from the docs.
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
note that explode has a limit function. So you could do something like
$message = implode(" ", explode(" ", $long_message, 20));
Try regex.
You need something that would match 20 words (or 20 word boundaries).
So (my regex is terrible so correct me if this isn't accurate):
/(\w+\b){20}/
And here are some examples of regex in php.
Simple and fully equiped truncate() method:
function truncate($string, $width, $etc = ' ..')
{
$wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2);
return $wrapped[0] . (isset($wrapped[1]) ? $etc : '');
}
Its not my own creation, its a modification of previous posts. credits goes to karim79.
function limit_text($text, $limit) {
$strings = $text;
if (strlen($text) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
if(sizeof($pos) >$limit)
{
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
return $text;
}
If you code on Laravel just use Illuminate\Support\Str
here is example
Str::words($category->publication->title, env('WORDS_COUNT_HOME'), '...')
Hope this was helpful.
Split the string (into an array) by <space>, and then take the first 20 elements of that array.
With triple dots:
function limitWords($text, $limit) {
$word_arr = explode(" ", $text);
if (count($word_arr) > $limit) {
$words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
return $words;
}
return $text;
}
Try below code,
$text = implode(' ', array_slice(explode(' ', $text), 0, 32))
echo $text;
Something like this could probably do the trick:
<?php
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));
use PHP tokenizer function strtok() in a loop.
$token = strtok($string, " "); // we assume that words are separated by sapce or tab
$i = 0;
$first20Words = '';
while ($token !== false && $i < 20) {
$first20Words .= $token;
$token = strtok(" ");
$i++;
}
echo $first20Words;
based on 動靜能量's answer:
function truncate_words($string,$words=20) {
return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
}
or
function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
$new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
if($new != $string){
return $new.$ellipsis;
}else{
return $string;
}
}
This worked me for UNICODE (UTF8) sentences too:
function myUTF8truncate($string, $width){
if (mb_str_word_count($string) > $width) {
$string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
}
return $string;
}
Here is what I have implemented.
function summaryMode($text, $limit, $link) {
if (str_word_count($text, 0) > $limit) {
$numwords = str_word_count($text, 2);
$pos = array_keys($numwords);
$text = substr($text, 0, $pos[$limit]).'... Read More';
}
return $text;
}
As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.
I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.
Here's one I use:
$truncate = function( $str, $length ) {
if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
$str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
return htmlspecialchars($str[0]) . '…';
} else {
return htmlspecialchars($str);
}
};
return $truncate( $myStr, 50 );
Another solution :)
$aContent = explode(' ', $cContent);
$cContent = '';
$nCount = count($aContent);
for($nI = 0; ($nI < 20 && $nI < $nCount); $nI++) {
$cContent .= $aContent[$nI] . ' ';
}
trim($cContent, ' ');
echo '<p>' . $cContent . '</p>';
To limit words, am using the following little code :
$string = "hello world ! I love chocolate.";
$explode = array_slice(explode(' ', $string), 0, 4);
$implode = implode(" ",$explode);
echo $implode;
$implot will give : hello world ! I
function getShortString($string,$wordCount,$etc = true)
{
$expString = explode(' ',$string);
$wordsInString = count($expString);
if($wordsInString >= $wordCount )
{
$shortText = '';
for($i=0; $i < $wordCount-1; $i++)
{
$shortText .= $expString[$i].' ';
}
return $etc ? $shortText.='...' : $shortText;
}
else return $string;
}
Simpler than all previously posted regex techniques, just match the first n sequences of non-word followed by sequences of word characters. Making the non-word characters optional allows matching of word characters from the start of the string. Greedy word character matching ensures that consecutive word characters are never treated as individual words.
By writing \K in the pattern after matching n substrings, then matching the rest of the string (add the s pattern modifier if you need dots to match newlines), the replacement can be an empty string.
Code: (Demo)
function firstNWords(string $string, int $limit = 3) {
return preg_replace("/(?:\W*\w+){{$limit}}\K.*/", '', $string);
}
Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:
script_tags() PHP function to remove the unnecessary HTML and PHP
tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
explode() to split the $string into an array
array_splice() to specify the number of words and where it'll start
from. It'll be controlled by vallues assigned to our $start and $limit variables.
and finally, implode() to join the array elements into your truncated
string..
function truncateString($string, $start, $limit){
$stripped_string =strip_tags($string); // if there are HTML or PHP tags
$string_array =explode(' ',$stripped_string);
$truncated_array = array_splice($string_array,$start,$limit);
$truncated_string=implode(' ',$truncated_array);
return $truncated_string;
}
It's that simple..
I hope this was helpful.
I made my function:
function summery($text, $limit) {
$words=preg_split('/\s+/', $text);
$count=count(preg_split('/\s+/', $text));
if ($count > $limit) {
$text=NULL;
for($i=0;$i<$limit;$i++)
$text.=$words[$i].' ';
$text.='...';
}
return $text;
}
function limitText($string,$limit){
if(strlen($string) > $limit){
$string = substr($string, 0,$limit) . "...";
}
return $string;
}
this will return 20 words. I hope it will help
$text='some text';
$len=strlen($text);
$limit=500;
// char
if($len>$limit){
$text=substr($text,0,$limit);
$words=explode(" ", $text);
$wcount=count($words);
$ll=strlen($words[$wcount]);
$text=substr($text,0,($limit-$ll+1)).'...';
}
function wordLimit($str, $limit) {
$arr = explode(' ', $str);
if(count($arr) <= $limit){
return $str;
}
$result = '';
for($i = 0; $i < $limit; $i++){
$result .= $arr[$i].' ';
}
return trim($result);
}
echo wordLimit('Hello Word', 1); // Hello
echo wordLimit('Hello Word', 2); // Hello Word
echo wordLimit('Hello Word', 3); // Hello Word
echo wordLimit('Hello Word', 0); // ''
I would go with explode() , array_pop() and implode(), eg.:
$long_message = "I like summer, also I like winter and cats, btw dogs too!";
$trimmed_message = explode(" ", $long_message, 5); // <-- '5' means 4 words to be returned
array_pop($trimmed_message); //removing last element from exploded array
$trimmed_message = implode(" ", $trimmed_message) . '...';
Result:
I like summer, also...
what about
chunk_split($str,20);
Entry in the PHP Manual
function limit_word($start,$limit,$text){
$limit=$limit-1;
$stripped_string =strip_tags($text);
$string_array =explode(' ',$stripped_string);
if(count($string_array)>$limit){
$truncated_array = array_splice($string_array,$start,$limit);
$text=implode(' ',$truncated_array).'...';
return($text);
}
else{return($text);}
}
How can I adapt this function below to get string between numbers?
Function:
function getInbetweenStrings($start, $end, $str){
$matches = array();
$regex = "/$start([a-zA-Z0-9_]*)$end/";
preg_match_all($regex, $str, $matches);
return $matches[1];
}
Example:
1448459casa48912687
010697046a-parede-verde698012
456902sim-senhora4401254
Output expected:
casa
a-parede-verde
sim-senhora
Thank you.
#edit: I don't want to remove all numbers, I need them! I just want grab string between.
You can use this regex, which looks for a minimal sequence (by adding ? to .*) of characters between starting and trailing digits:
^\d+(.*?)\d+$
In PHP:
$strings = array('1448459casa48912687',
'010697046a-parede-verde698012',
'456902sim-senhora4401254',
'12345number10-downing-street54321');
foreach ($strings as $string) {
$between = preg_replace('/^\d+(.*?)\d+$/', '$1', $string);
echo "$between\n";
}
Output:
casa
a-parede-verde
sim-senhora
number10-downing-street
Demo on 3v4l.org
If the strings are different (ie: [foo] & [/foo])
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = '010697046a-parede-verde698012';
$parsed = get_string_between($fullstring, '010697046a', '698012');
echo $parsed; // (result = a-parede-verde)
I have a function that extracts the content between a $start and $end inside a $string
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
The problem with this is that it will only get me the first occurrence found in the string. Per example:
$text = "John has 13 oranges and Jane has 8 oranges";
$how_many_oranges = get_string_between($text,"has "," oranges");
echo $how_many_oranges; // echos "13"
I need it to find the last occurrence inside the string, so that $how_many_oranges = "8";
As mentioned in my comment, swap out strpos() for strrpos()
Find the numeric position of the last occurrence of needle in the haystack string.
Also, I believe you should change
if ($ini == 0)
to
if ($ini === false)
The former will match if $start is at the very beginning of $string. The latter will match if $start cannot be found at all.
Demo ~ https://eval.in/1027283
What about using just PHP's built in function?!
strripos() – Finds the position of the last occurrence of a string inside another string. It is a Case-insensitive.
PHP Docs
I took the liberty to rewrote your code, to make it, IMHO, more readable and self-explanatory :)
I'd also recommend you to use the strrpos:
function getStringBetween($string, $start, $end) {
$lastStartIndex = strrpos($string, $start);
$lastEndIndex = strrpos($string, $end);
$substringStartIndex = $lastStartIndex + strlen($start);
$substringSize = $lastStartIndex - $lastEndIndex - 1;
return substr($string, $substringStartIndex, $substringSize);
}
$text = "John has 13 oranges and Jane has 8 oranges";
$how_many_oranges = getStringBetween($text, "has", "oranges");
echo "'" . $how_many_oranges . "'"; // echos "' 8 '"
Try this:
function get_string_between($string, $start, $end){
$p1 = explode($start,$str);
for($i=1;$i<count($p1);$i++){
$p2 = explode($end,$p1[$i]);
$p[] = $p2[0];
}
return $p;
}
source: stackoverflow.com/a/45033158
This looks like a reasonable time to use regular expressions.
function get_string_between($string, $start, $end) {
$clean_start = preg_quote($start, '/');
$clean_end = preg_quote($end, '/');
$pattern = "/.*$clean_start (.*) $clean_end.*/U"; // U modifier => ungreedy
$default_result = ''; // returned if no matches found
$matches;
preg_match_all($pattern, $string, $matches);
return (count($matches[1]) > 0) ? end($matches[1]) : $default_result;
}
echo get_string_between('John has 13 oranges and Jane has 8 oranges', 'has', 'oranges'); // 8
My string is: "reply-234-private", i want to get the number after "reply-" and before "-private", it is "234". I have tried with following code but it returns an empty result:
$string = 'reply-234-private';
$display = preg_replace('/reply-(.*?)-private/','',$string);
echo $display;
You can just explode it:
<?php
$string = 'reply-234-private';
$display = explode('-', $string);
var_dump($display);
// prints array(3) { [0]=> string(5) "reply" [1]=> string(3) "234" [2]=> string(7) "private" }
echo $display[1];
// prints 234
Or, use preg_match
<?php
$string = 'reply-234-private';
if (preg_match('/reply-(.*?)-private/', $string, $display) === 1) {
echo $display[1];
}
Have a look at explode() function
something like this:
$myString = 'reply-234-private';
$myStringPartsArray = explode("-", $myString);
$answer = $myStringPartsArray[1];
This article show you, How to get of everything string between two tags or two strings.
http://okeschool.com/articles/312/string/how-to-get-of-everything-string-between-two-tag-or-two-strings
<?php
// Create the Function to get the string
function GetStringBetween ($string, $start, $finish) {
$string = " ".$string;
$position = strpos($string, $start);
if ($position == 0) return "";
$position += strlen($start);
$length = strpos($string, $finish, $position) - $position;
return substr($string, $position, $length);
}
?>
in case your question, you can try this :
$string1='reply-234-private';
echo GetStringBetween ($string1, "-", "-")
or we can use any 'identifier string' for grab the string between the identifier string. for example:
echo GetStringBetween ($string1, "reply-", "-private")
Use php's inbuilt regex support functions
preg_match_all
this would help, suppose you want the array of strings(keys) between ## in following example, where '/' doesn't fall in-between, you can built new example with different start an end variable
function getInbetweenStrings($start, $end, $str){
$matches = array();
$regex = "/$start([a-zA-Z0-9_]*)$end/";
preg_match_all($regex, $str, $matches);
return $matches[1];
}
$str = "C://##ad_custom_attr1##/##upn##/##samaccountname##";
$str_arr = getInbetweenStrings('##', '##', $str);
print_r($str_arr);
$myString = 'reply-234-private';
echo str_replace('-','',filter_var($myString,FILTER_SANITIZE_NUMBER_INT));
That should do the job.
If you want to do it in js, try this function -
function getStringBetween(str , fromStr , toStr){
var fromStrIndex = str.indexOf(fromStr) == -1 ? 0 : str.indexOf(fromStr) + fromStr.length;
var toStrIndex = str.slice(fromStrIndex).indexOf(toStr) == -1 ? str.length-1 : str.slice(fromStrIndex).indexOf(toStr) + fromStrIndex;
var strBtween = str.substring(fromStrIndex,toStrIndex);
return strBtween;
}