Why is this strpos() returning an error?

I’m trimming a string in an excerpt as follows:

$mod_trim_to = strpos(get_the_excerpt(), ' ', 115);
$trimmed_exceprt = substr(get_the_excerpt(),0,$mod_trim_to);

The goal here is to trim the excerpt to 115 characters in cases where it’s being auto-generated and breaking the bounds of a very small space, as specified by the third party graphic designer.

Read More

The function returns properly, but also throws a warning:

PHP Warning:  strpos(): Offset not contained in string

I can only guess that strpos() doesn’t like searching for a space? What is the correct way to write this so I don’t end up with an error log?

Thanks

Related posts

Leave a Reply

1 comment

  1. Full example with Sverri M. Olsen’s recommendations:

    $maxLength = 115;
    $excerpt = get_the_excerpt();
    
    if (strlen($string) > $maxLength) {
        $modTrimTo = strpos($excerpt, ' ', $maxLength);
        $trimmedExcerpt = substr($excerpt, 0, $modTrimTo);
    } else {
        $trimmedExcerpt = $excerpt;
    }
    

    But be careful: if you have utf8 encoded excerpts, use this:

    strlen(utf8_decode($excerpt));
    

    or this:

    mb_strlen($excerpt, 'UTF-8')