I'm trying to show part of a string; 60 characters of it. But it's cut and not displayed to while word. So I tried this:
if(strpos($string, ' ', 50) !== FALSE) {
substr($string, 0, strpos($string, ' ', 50))
}elseif(strlen($string) < 50)) {
echo $string;
}
But now, problem is that I don't know after how many characters there is space. I've checked if there is space after 50 characters and show this sub-string. But if word is with many characters, how to check its length, so that my final sub-string is not more than 60 characters?
Is there better solution to this kind of showing sub-string to whole word?
Consider this example:
<?php
$subject = <<<EOT
But now, problem is that I don't know after how many characters there is space.
I've checked if there is space after 50 characters and show this substring.
But if word is with many characters, how to check its length, so that my final substring is not more than 60 characters?
EOT;
$lastBlankPos = strrpos(substr($subject, 0, 60), ' ');
var_dump(substr($subject, 0, $lastBlankPos));
The output is:
string(52) "But now, problem is that I don't know after how many"
The strategy is: look for the last blank contained in the first 60 characters of the string. This guarantees that you terminate your substring with a "whole word" whilst still staying right under 60 characters in length. strrpos()
is a handy function for that: http://php.net/manual/en/function.strrpos.php