Make sure sub string functions finishes on a word not a character
We know how to use the substr function but this function return the output in middle of word, but it looks odd when some time showing half of word, to solve this problem we can use both Javascript or PHP. Bellow both language example given for your help to substruct your string to end at the end of a word.
Make sure sub string functions finishes on a word not a character. Solution in PHP
<?php
$string = 'My country name is bangladesh and my name is Rasel.';
echo substr($string, 0, strpos($string, ' ', 30)).' ..';
echo '<br/>';
echo substr($string, 0, strpos($string, ' ', 33)).' ..';
echo '<br/>';
echo substr($string, 0, strpos($string, ' ', 40)).' ..';
//For UTF8 Character set use mb_substr() function insted of substr
?>
Here the output of the above php code will look likes bellow:
My country name is bangladesh and .. My country name is bangladesh and .. My country name is bangladesh and my name ..
Make sure sub string functions finishes on a word not a character. Solution in Javascript
<script>
function trim_words(theString, numWords) {
expString = theString.split(/\s+/,numWords);
theNewString=expString.join(" ");
return theNewString;
}
var test = trim_words('My country name is bangladesh and my name is Rasel.', 5)
alert(test);
</script>
The above javascript function will give the output like bellow:
My country name is bangladesh ..