Forum Moderators: coopster

Message Too Old, No Replies

substr at a space only

         

RussellC

4:38 pm on Dec 8, 2004 (gmt 0)

10+ Year Member



I am looking for a function that is just like substring where i can cut a long sentence into 2 halves at a certain number a characters. But I dont want it to break up any words, so it can only cut it at a space. Something like this:

$latestupdate1 = substr($latestupdate, 0, 109);
$latestupdate2 = substr($latestupdate, 109);

but without cutting at a space.

Thanks.

CaseyRyan

4:51 pm on Dec 8, 2004 (gmt 0)

10+ Year Member



This was totally a question on a test I had in college. :)

The answer:
The way you do it is pick your midpoint. Looks like you've chosen 109. Then work backwards 1 character at a time, until you hit a space character. So, you'll check the character at 109, 108, 107... until you hit a space. When you do hit the space (say 104), you'll return the substring up to 104. If you have to split the rest of the string, you can start at the length of the returned value + 1.

As far as I know, you'll have to write that function.

-=casey=-

RussellC

5:25 pm on Dec 8, 2004 (gmt 0)

10+ Year Member



thanks for the response, you got my thinking going in the right path. This seems to work:

<?php
$x = 109;
$testchar = substr($latestupdate, $x, 1);
while ($testchar!= " ") {
$x = $x - 1;
$testchar = substr($latestupdate, $x, 1);
}
$latestupdate1 = substr($latestupdate, 0, $x);
$latestupdate2 = substr($latestupdate, $x);
?>

adb64

9:37 pm on Dec 8, 2004 (gmt 0)

10+ Year Member



PHP has a function for this: wordwrap [php.net]

Arjan