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.
Check if string fits designated box
Moderator: General Moderators
- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
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.
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.';- stereofrog
- Forum Contributor
- Posts: 386
- Joined: Mon Dec 04, 2006 6:10 am
Re: Check if string fits designated box
Since we're in the regexp forum, here's a regexp solution: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.
Code: Select all
if(preg_match('/^(.{1,70})\s(.{1,70})$/', $text))
# $text can fit onto 2 lines
else
# $text doesn't fitNice 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.
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