tags:

views:

61

answers:

2

This is more of underlying PHP execution question.

What are the positives or negatives to the two following methods for limiting string size?

function max_length($string, $length) {
  return (strlen($string) > $length)?substr($string, 0, $length):$string;
}

substr($string, 0, $length);

The case I am worried about is when the string is smaller than the length requested. Can it cause buffer overflow errors? Extra whitespace? Repeated characters?

The only thing I do know is that speed-wise, substr is at least 2x faster than the custom function provided.

+2  A: 

As you can see in http://us2.php.net/substr

If length  is given and is positive, the string returned will contain
at most length  characters beginning from start  (depending on the
length of string ). 

That means you won't get any extra characters, just the ones you're asking for.

Seb
A: 

No, nothing to worry about. If the specified length argument is higher than the length of the string - the whole string, and nothing else - will be returned. So just go with:

$maxString = substr($string, 0, $length);
Björn