I am trying to limit the number of characters returned from a string using PHP.
I've applied a solution that seems to crash the server (high load / infinite loop), so I am asking for alternative.
I am trying to find a solution that cuts the string and displays the specific number of characters, but still respects the meaning of the sentence, i.e. it does not make a cut in the middle of the word
My function call is as follows:
<?php
uc_textcut(get_the_title());
?>
And in my functions.php this is the code I used (and it does crash):
function uc_textcut($var) {
$position = 60;
$result = substr($var,$position,1);
if ($result !=" ") {
while($result !=" ") {
$i = 1;
$position = $position+$i;
$result = substr($var,$position,1);
}
}
$result = substr($var,0,$position);
echo $result;
echo "...";
}
My problem is with $position = 60
.
The higher that number, the more load it takes -- like its doing a very slow loop.
I imagine something is wrong with while()
, but I am trying to keep it still understandable by the visitor, again, not cutting in the middle of word.
Any input?
:) thanks very much guys