Page 1 of 1

Check if string fits designated box

Posted: Sun Sep 23, 2007 3:38 am
by h123z
I need to check if a string fits onto 2 lines of 70 characters each, without splitting in middle of a word.
i.e, if the 71st character is not a space, i need to see if the length from the previous space till the end of string is greater than 70.

Any help would be appreciated- I'm a bit of a newbie to php.

Posted: Sun Sep 23, 2007 7:06 am
by superdezign
Well, wordwrap() would be a good choice for limiting line lengths, and it doesn't break in the middle of words unless you specify for it to do so. From there, you can use explode(), array_splice() (or other array functions) and implode() together or strpos and substr() together. You may also want to strip newlines before using wordwrap() to avoid glitches in the following steps.

Posted: Sun Sep 23, 2007 9:16 am
by GeertDD

Code: Select all

// Example string
$str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';

// Split string in two parts
// Take 71 chars (not 70) for first part because 71th char can be a space without a problem
$half1 = substr($str, 0, 71);

// Position of the last space in the first part of the string
// In case of no space at all (might happen), cast to integer = position 0
$lastspace = (int) strrpos($half1, ' ');

// Second line starts from that position
// Chop off leading and trailing whitespace as well
$line2 = trim(substr($str, $lastspace));

// Just check length of the second line now to check if it would fit
if (strlen($line2) > 70)
	echo 'String does NOT fit designated box.';
else
	echo 'String does fit designated box.';

Re: Check if string fits designated box

Posted: Mon Sep 24, 2007 6:36 am
by stereofrog
h123z wrote:I need to check if a string fits onto 2 lines of 70 characters each, without splitting in middle of a word.
i.e, if the 71st character is not a space, i need to see if the length from the previous space till the end of string is greater than 70.
Since we're in the regexp forum, here's a regexp solution:

Code: Select all

if(preg_match('/^(.{1,70})\s(.{1,70})$/', $text))
   # $text can fit onto 2 lines
else
   # $text doesn't fit

Posted: Mon Sep 24, 2007 10:55 am
by GeertDD
Nice one, stereofrog!

Using regex appears to be just a bit faster as well in this case.

Here's an updated version of your regex. Before it would choke on empty strings and on single word strings.

Code: Select all

if (preg_match('/^.{0,70}(?:\s.{0,70})?$/', $text))
   # $text can fit onto 2 lines
else
   # $text doesn't fit