agvr3 agvr3 - 4 months ago 14
PHP Question

With PHP substr, how can I find the previous whitespace instead of the following whitespace?

I would like to crop off a string at the whitespace before the word which is cut off. Currently I have working code for cropping off a string at the whitespace after the word which is cut off, but this exceeds my max char limit.

I did some experimenting and I was able to find a solution to find the whitespace, so that instead of cropping off the middle of a word, strpos will instead find the whitespace after the word which falls within the character limit and then crop the string.

$thestring = "my really really really really really really really";
$getlength = strlen($thestring);
$maxLength = 42;

if ($getlength > $maxLength) {
echo substr($thestring, 0, strpos($thestring, ' ', $maxLength));
echo "...";
} else {
echo $thestring;
}
echo " - long string";


This is fully working, the only thing, is that I want to put a hard limit to the number of characters in the string. But what this does is crop after the word it falls between, which puts it a few characters over the limit.

For example, this will return this string:

my really really really really really really - long string


because 42 characters falls on the last "really", so it extends the length to the next whitespace. But now the returned string is 44 characters.

What I would rather like it to do, is that since the exact 42 characters returns:

my really really really really really real


then, instead, I would like to crop it to the prior whitespace, not the following whitespace. So like in this example, I would like this returned:

my really really really really really - long string


This is good, because it crops off the last partial word, so instead of returning just part of the last word
real
which looks bad, or after the whole word
really
which exceeds my max character limit, then instead it crops the partial last word causing the total string to fall below the max limit, which is what I want.

So like my desired returned string above would be 37 characters, which is what I want because it's less than 42.

So, how can I modify my code to crop it at the prior whitespace to the word which the end of the maxLength falls on, rather than the following whitespace?

Answer

Ok. I don't know why my sample of code didn't work for you (it's really strange) :-/

But this is the full code based on your source:

<?php
$thestring = "my really really really really really really really";
$getlength = strlen($thestring);
$maxLength = 42;

if ($getlength > $maxLength) {
    echo substr($thestring, 0, strrpos($thestring, ' ', $maxLength-$getlength));
    echo "...";
} else {
    echo $thestring;
}
echo " - long string";

for my console it outputs:

   [64] $ php ./ex.php
   my really really really really really... - long string
Comments