Related
How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
Update 2:
Or as function:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
This functionality has been built into PHP since version 4.0.6. See the docs.
echo mb_strimwidth('Hello World', 0, 10, '...');
// outputs Hello W...
Note that the trimmarker (the ellipsis above) are included in the truncated length.
The Multibyte extension can come in handy if you need control over the string charset.
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
$string = mb_substr($string, 0, $length - 3, $charset) . '...';
}
sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.
eg:
we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.
phew, am bad at explaining, here is the code.
class Fun {
public function limit_text($text, $len) {
if (strlen($text) < $len) {
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word) {
if ((strlen($word) > $len) && $out == null) {
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len) {
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
If you want to cut being careful to don't split words you can do the following
function ellipse($str,$n_chars,$crop_str=' [...]')
{
$buff=strip_tags($str);
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return $buff;
}
if $str is shorter than $n_chars returns it untouched.
If $str is equal to $n_chars returns it as is as well.
if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
NOTE: be aware that this method will remove all tags in case of HTML.
The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html
(just read the word_limiter and character_limiter sections).
Here's two functions from it relevant to your question:
if ( ! function_exists('word_limiter'))
{
function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return rtrim($matches[0]).$end_char;
}
}
And
if ( ! function_exists('character_limiter'))
{
function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
}
}
}
}
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
Use substring
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
I'm not sure if this is the fastest solution, but it looks like it is the shortest one:
$result = current(explode("\n", wordwrap($str, $width, "...\n")));
P.S. See some examples here https://stackoverflow.com/a/17852480/131337
This function do the job without breaking words in the middle
function str_trim($str,$char_no){
if(strlen($str)<=$char_no)
return $str;
else{
$all_words=explode(" ",$str);
$out_str='';
foreach ($all_words as $word) {
$temp_str=($out_str=='')?$word:$out_str.' '.$word;
if(strlen($temp_str)>$char_no-3)//-3 for 3 dots
return $out_str."...";
$out_str=$temp_str;
}
}
}
The function I used:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
See it in action.
This is what i do
function cutat($num, $tt){
if (mb_strlen($tt)>$num){
$tt=mb_substr($tt,0,$num-2).'...';
}
return $tt;
}
where $num stands for number of chars, and $tt the string for manipulation.
I developed a function for this use
function str_short($string,$limit)
{
$len=strlen($string);
if($len>$limit)
{
$to_sub=$len-$limit;
$crop_temp=substr($string,0,-$to_sub);
return $crop_len=$crop_temp."...";
}
else
{
return $string;
}
}
you just call the function with string and limite
eg:str_short("hahahahahah",5);
it will cut of your string and add "..." at the end
:)
To create within a function (for repeat usage) and dynamical limited length, use:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
It's best to abstract you're code like so (notice the limit is optional and defaults to 10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
substr() would be best, you'll also want to check the length of the string first
$str = 'someLongString';
$max = 7;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...';
}
wordwrap won't trim the string down, just split it up...
$width = 10;
$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
or with wordwrap
$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
this solution will not cut words, it will add three dots after the first space.
I edited #Raccoon29 solution and I replaced all functions with mb_ functions so that this will work for all languages such as arabic
function cut_string($str, $n_chars, $crop_str = '...') {
$buff = strip_tags($str);
if (mb_strlen($buff) > $n_chars) {
$cut_index = mb_strpos($buff, ' ', $n_chars);
$buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
}
return $buff;
}
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
while(strlen($yourString) > 22) {
$pos = strrpos($yourString, " ");
if($pos !== false && $pos <= 22) {
$out = substr($yourString,0,$pos);
break;
} else {
$yourString = substr($yourString,0,$pos);
continue;
}
}
} else {
$out = $yourString;
}
echo "Output String: ".$out;
If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
In this case, $preview will be "Knowledge is a natural right of every human being".
Live code example:
http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713
I have different strings that are function names like
createWebsiteManagementUsers
I want to change them into
Create Website Mangement Users
How can i achieve that in PHP?
a) You can use ucwords():-
echo ucwords($string);
Output:- https://3v4l.org/sCiEJ
b) In your expected outcome spaces are there, if you want that then do:
echo ucwords(implode(' ',preg_split('/(?=[A-Z])/', 'createWebsiteManagementUsers')));
Output:- https://3v4l.org/v3KUK
Use below code to solve:
$String = 'createWebsiteManagementUsers';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
echo ucwords($Words);
//output will be Create Website Mangement Users
try this
$data = preg_split('/(?=[A-Z])/', 'createWebsiteManagementUsers');
$string = implode(' ', $data);
echo ucwords($string);
output will be
Create Website Management Users
Here is what you need. This has the spaces as well!
function parseCamelCase($camelCaseString){
$words_splited = preg_split('/(?=[A-Z])/',$camelCaseString);
$words_capitalized = array_map("ucfirst", $words_splited);
return implode(" ", $words_capitalized);
}
Thanks
function camelCaseToString($string)
{
$pieces = preg_split('/(?=[A-Z])/',$string);
$word = implode(" ", $pieces);
return ucwords($word);
}
$name = "createWebsiteManagementUsers";
echo camelCaseToString($name);
May be you can try something like this
//Split words with Capital letters
$pieces = preg_split('/(?=[A-Z])/', 'createWebsiteManagementUsers');
$string = implode(' ', $pieces);
echo ucwords($string);
//You will get your desire output Create Website Management Users
Try this:
preg_match_all('/((?:^|[A-Z])[a-z]+)/',$str,$matches);
100% Most Efficient :
$word = 'camelCase'; // expected: Camel Case
$sentence = modifyWord($word);
function modifyWord($word)
{
$splittedWord = str_split($word);
$modifiedSentence = ucwords($splittedWord[0]);
for($i = 1; $i < count($splittedWord); $i++){
// ASCII : A => 65, Z => 90
// check if the letter is between A & Z
if(ord($splittedWord[$i]) >= 65 && ord($splittedWord[$i]) <= 90){
$modifiedSentence .= ' '.$splittedWord[$i];
}else{
$modifiedSentence .= $splittedWord[$i];
}
}
return $modifiedSentence;
}
Fixed version with UPPER letter check and symbols
<?php
$word = 'UniCredit Bank (AA)'; // expected: Camel Case
$word = 'CamelCase with space (CAPITAL_NAME) and strangEEword'; // expected: Camel Case
$sentence = modifyWord($word);
echo $sentence;
function modifyWord($word)
{
$splittedWord = str_split($word);
$modifiedSentence = ucwords($splittedWord[0]);
for($i = 1; $i < count($splittedWord); $i++){
// ASCII : A => 65, Z => 90
// check if the letter is between A & Z
$nextCapital = isset($splittedWord[$i+1]) && ord($splittedWord[$i+1]) >= 65 && ord($splittedWord[$i+1]) <= 90;
$prevCapital = isset($splittedWord[$i-1]) && ord($splittedWord[$i-1]) >= 65 && ord($splittedWord[$i-1]) <= 90;
if(ord($splittedWord[$i]) >= 65 && ord($splittedWord[$i]) <= 90 && !$nextCapital && !$prevCapital){
$modifiedSentence .= ' '.$splittedWord[$i];
}else{
$modifiedSentence .= $splittedWord[$i];
}
}
return $modifiedSentence;
}
I just want to know if there is any built in php function where I can get a substring between given two keywords (keyword1 and keyword2). Note that keywords may repeat in the string so I must be able to get the substring between xth keyword1 and yth keyword2. Moreover, I mainly use unicode characters so the function should be charset independen.
Please help me out to handle this problem.
E.g. $string=This is their cat with a hat in the theater.
$keyword1="is"; $keyword2="the";
Task: how to get substring between 2nd occurance of "is" and 3nd occurance of "the" in the given string above.
Answer: " the cat with a hat in the "
You can use regular expressions:
$string = "This is their cat with a hat in the theater";
$regex1 = "/.*? is |^is/";
$regex2 = "/ the .*| the$/";
echo preg_replace($regex1, '', preg_replace($regex2, ' the', $string));
EDIT Here is more generic code:
function find($text, $str, $offset) {
$len = strlen($text);
$search_len = strlen($str);
$count = 0;
for ($i=0; $i<$len; ++$i) {
if (substr($text, $i, $search_len) == $str) {
if (++$count == $offset) {
return $i;
}
}
}
return -1;
}
function between($text, $word1, $offset1, $word2, $offset2) {
$start = find($text, $word1, $offset1);
$end = find($text, $word2, $offset2);
if ($start != -1 && $end != -1) {
return substr($text, $start + strlen($word1), $end-$start-strlen($word2));
} else {
return '';
}
}
$string = "This is their cat with a hat in the theater";
echo between($string, 'is', 2, 'the', 3);
echo between($string, 'at', 1, 'at', 3);
Combination of following two functions work for any string including unicode characters:
//Gets the position of a given substring with its offset;
function strposOffset($string, $search, $offset)
{
/*** explode the string ***/
$arr = explode($search, $string);
/*** check the search is not out of bounds ***/
switch( $offset )
{
case $offset == 0:
return false;
break;
case $offset > max(array_keys($arr)):
return false;
break;
default:
return mb_strlen(implode($search, array_slice($arr, 0, $offset)), "utf-8");
}
} //Source: www.phpro.org
//Extracts a substring between given two given substrings with their offsets.
function extractMiddleSubstr($string, $substr1, $offset1, $substr2, $offset2){
$strlen_substr1 = mb_strlen($substr1, "utf-8"); //length of substr1;
$strpos_substr1 = strposOffset($string, $substr1, $offset1); //position of substr1;
$strpos_substr2 = strposOffset($string, $substr2, $offset2); //position of substr2;
if($strpos_substr1!==null && $strpos_substr2!==null && $strpos_substr1!==false && $strpos_substr2!==false){
if($strpos_substr1<=$strpos_substr2){
$strpos_substr = $strlen_substr1+$strpos_substr1; //position of substr;
$strlen_substr = $strpos_substr2-$strpos_substr; //length of substr;
$substr = mb_substr($string, $strpos_substr, $strlen_substr, "utf-8"); //substr;
$substr = trim($substr); // removes whitespaces;
return $substr;
}else{
return false;
}
}else{
return false;
}
}
whats is the best way to replace all commas for XX(a,s,d,f) into pipes in a long string like
`exp` x(10) XX('s','44','f','dd','sddd') some other text here, text here , other text here
i want to replace commas only in this XX('s','44','f','dd','sddd') part [commas only in the brackets]
Maybe something like:
while (preg_match('/\((.*),(.*)\)/', $foo))
$foo = preg_replace('/\((.*),(.*)\)/', '($1|$2)', $foo);
A simple string parser would probably be quicker than a regex. DEMO.
<?php
$string = "`exp` x(10) XX('s','44','f','dd','sddd') some other text here, text here , other text here";
$inParentheses = false;
for ($i = 0; $i < strlen($string); $i++) {
if ($inParentheses) {
if ($string[$i] == ")") {
$inParentheses = false;
} else if ($string[$i] == ",") {
$string[$i] = "|"; //The replacement character
}
} else if ($string[$i] == "(") {
$inParentheses = true;
}
}
var_dump($string);
?>
this is how i fixed it but still open for other solutions
while (preg_match('/\(([^\)]*)\)/', $tableCols)){
$tableCols = preg_replace('/\(([^\)]*)\)/e','"[[[".str_replace(\',\',\'|\',\'$1\')."]]]"', $tableCols);
}
$tableCols = str_replace('[[[', '(', $tableCols);
$tableCols = str_replace(']]]', ')', $tableCols);
How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
Update 2:
Or as function:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
This functionality has been built into PHP since version 4.0.6. See the docs.
echo mb_strimwidth('Hello World', 0, 10, '...');
// outputs Hello W...
Note that the trimmarker (the ellipsis above) are included in the truncated length.
The Multibyte extension can come in handy if you need control over the string charset.
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
$string = mb_substr($string, 0, $length - 3, $charset) . '...';
}
sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.
eg:
we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.
phew, am bad at explaining, here is the code.
class Fun {
public function limit_text($text, $len) {
if (strlen($text) < $len) {
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word) {
if ((strlen($word) > $len) && $out == null) {
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len) {
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
If you want to cut being careful to don't split words you can do the following
function ellipse($str,$n_chars,$crop_str=' [...]')
{
$buff=strip_tags($str);
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return $buff;
}
if $str is shorter than $n_chars returns it untouched.
If $str is equal to $n_chars returns it as is as well.
if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
NOTE: be aware that this method will remove all tags in case of HTML.
The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html
(just read the word_limiter and character_limiter sections).
Here's two functions from it relevant to your question:
if ( ! function_exists('word_limiter'))
{
function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return rtrim($matches[0]).$end_char;
}
}
And
if ( ! function_exists('character_limiter'))
{
function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
}
}
}
}
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
Use substring
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
I'm not sure if this is the fastest solution, but it looks like it is the shortest one:
$result = current(explode("\n", wordwrap($str, $width, "...\n")));
P.S. See some examples here https://stackoverflow.com/a/17852480/131337
This function do the job without breaking words in the middle
function str_trim($str,$char_no){
if(strlen($str)<=$char_no)
return $str;
else{
$all_words=explode(" ",$str);
$out_str='';
foreach ($all_words as $word) {
$temp_str=($out_str=='')?$word:$out_str.' '.$word;
if(strlen($temp_str)>$char_no-3)//-3 for 3 dots
return $out_str."...";
$out_str=$temp_str;
}
}
}
The function I used:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
See it in action.
This is what i do
function cutat($num, $tt){
if (mb_strlen($tt)>$num){
$tt=mb_substr($tt,0,$num-2).'...';
}
return $tt;
}
where $num stands for number of chars, and $tt the string for manipulation.
I developed a function for this use
function str_short($string,$limit)
{
$len=strlen($string);
if($len>$limit)
{
$to_sub=$len-$limit;
$crop_temp=substr($string,0,-$to_sub);
return $crop_len=$crop_temp."...";
}
else
{
return $string;
}
}
you just call the function with string and limite
eg:str_short("hahahahahah",5);
it will cut of your string and add "..." at the end
:)
To create within a function (for repeat usage) and dynamical limited length, use:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
It's best to abstract you're code like so (notice the limit is optional and defaults to 10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
substr() would be best, you'll also want to check the length of the string first
$str = 'someLongString';
$max = 7;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...';
}
wordwrap won't trim the string down, just split it up...
$width = 10;
$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
or with wordwrap
$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
this solution will not cut words, it will add three dots after the first space.
I edited #Raccoon29 solution and I replaced all functions with mb_ functions so that this will work for all languages such as arabic
function cut_string($str, $n_chars, $crop_str = '...') {
$buff = strip_tags($str);
if (mb_strlen($buff) > $n_chars) {
$cut_index = mb_strpos($buff, ' ', $n_chars);
$buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
}
return $buff;
}
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
while(strlen($yourString) > 22) {
$pos = strrpos($yourString, " ");
if($pos !== false && $pos <= 22) {
$out = substr($yourString,0,$pos);
break;
} else {
$yourString = substr($yourString,0,$pos);
continue;
}
}
} else {
$out = $yourString;
}
echo "Output String: ".$out;
If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
In this case, $preview will be "Knowledge is a natural right of every human being".
Live code example:
http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713