kavoir.com kavoir.com - 25 days ago 10
PHP Question

Check if a string longer than xx characters without going through the entire string with strlen()?

I'm displaying some very very long text strings with a show more link. So I need a way to find out how long the string is.

I know I can simply use

strlen()
to size the string up and then compare the returned length against a limit like 50 characters but for very long strings I think it's a performance drag, especially considering there are nearly a thousand strings to be gauged per user request.

So is there any way to just make sure if the string is longer than 50 characters and then stop?

I know I can make an in-house function to go through the string character by character but is there any better practice in this case as I believe this is a rather common problem?

Answer Source

If the only thing you need to check if the string is longer then 50 characters, then you can try to check if the 50th character exists.

For example, for a string of 25 chars long I need to know if it's longer then 20 characters or not.

    $str = '123456789qwertyuiopasdfgh';
    if($str[20] != '') echo 'It is longer';
    else echo 'It is not';

I'm not sure if it's faster then simple strlen, but you can try some performance tests C:

UPD: Also, note that the index starts from 0