[PHP] cut off 160 chars

diabolo

Community Advocate
Community Support
Messages
1,682
Reaction score
32
Points
48
I want to write up a script to separate a message if it is >160 chars, and if it is separate it to as many as needed.

this is what I have so far
PHP:
// < 160 > ?
$lengthover = strlen($message);
if($lengthover > 160){
  $messagepart_1 = substr($message, 160);
}

but what happens if 160th character is in the middle of a word
 

xPlozion

New Member
Messages
868
Reaction score
1
Points
0
if it's in the middle of a word, it will split the word. say your last word is 'hello', it will split it at 'he' if that's where the 160th char falls. i've seen various custom functions if it falls within a word, but i forget it, i'll try to look it up for you.

[EDIT]
try:
PHP:
<?php
// Credit goes to: svihel
// http://us3.php.net/manual/en/function.substr.php#84103

function cutText($string, $setlength) {
    $length = $setlength;
    if($length<strlen($string)){
        while (($string{$length} != " ") AND ($length > 0)) {
            $length--;
        }
        if ($length == 0) return substr($string, 0, $setlength);
        else return substr($string, 0, $length);
    }else return $string;
}
?>
 
Last edited:

diabolo

Community Advocate
Community Support
Messages
1,682
Reaction score
32
Points
48
that's what I was trying to fix, if it falls in the middle of the word it would cut off at the beginning of the word rather than the middle
 

xPlozion

New Member
Messages
868
Reaction score
1
Points
0
found it at php.net. it's in my first post as an edit.
PHP:
<?php
// Credit goes to: svihel
// http://us3.php.net/manual/en/function.substr.php#84103

function cutText($string, $setlength) {
    $length = $setlength;
    if($length<strlen($string)){
        while (($string{$length} != " ") AND ($length > 0)) {
            $length--;
        }
        if ($length == 0) return substr($string, 0, $setlength);
        else return substr($string, 0, $length);
    }else return $string;
}
?>

hope that works for you.
 

diabolo

Community Advocate
Community Support
Messages
1,682
Reaction score
32
Points
48
thanks xPlozion
hmm this brings me closer to my goal
 

natsuki

New Member
Messages
112
Reaction score
0
Points
0
There are many ways to do it and this one uses the function xPlozion posted. I could have made my own too.

PHP:
$lengthover = strlen($message);

$parts = $lengthover / 160;

$beg = 0;
$msg = array();

do // or a for loop too
{
    $msg_left = substr($message, $beg);

    $msg_part = cutText($msg_left, 160);
    $msg[] = $msg_part;

    $beg += strlen($msg_part);

    $parts--;
}
while ($parts >= 0);
// then access the $msg array using foreach or count()
I haven't tested it though..
 
Last edited:

xPlozion

New Member
Messages
868
Reaction score
1
Points
0
mind sharing function cutText()? although i think it just either returns one word separated by a space, or explodes it. i'm gonna go w/ the first :)
 

mephis

New Member
Messages
39
Reaction score
0
Points
0
regarding xPlozion's code, it would be faster to use a builtin php function instead of iterating:
PHP:
// instead of iterating like this
while (($string{$length} != " ") AND ($length > 0)) {
    $length--;
}
// call strrpos() function which returns
// the last occurrence of " " in $string from $setlength (offset)
$length = strrpos($string, " ", $setlength);

-----Edit:
Actually, I just came up with a recursive function to do just that :p
PHP:
function cut_text($string, $setlength, &$outarray=array()) {
	if (strlen($string)<=$setlength) {
		$outarray[] = $string;
	} else {
		$tmpstr = substr($string,0,$setlength);
		$length = strrpos($tmpstr, " ");
		$outarray[] = substr($tmpstr,0,$length);
		cut_text(trim(substr($string,$length)),$setlength,$outarray);
	}
}

// call function
cut_text($message, 160, $result);
// result is stored as an array in $result
var_dump($result);
 
Last edited:

natsuki

New Member
Messages
112
Reaction score
0
Points
0
That's a nice idea using strrpos() instead of looping so I thought of using it as well. But it seems it's limited to single character needles or searches and will still need looping in what I'm trying to achieve. If you can think of a better way to do it, that would be new knowledge to me as well.

I made a similar function but instead of breaking it at spaces, it tries to break the words at certain boundaries like punctuations. If the word is longer than the length specified then it will be split apart depending on the length.

PHP:
<?php

// This function will try to split the string at word boundaries as much as possible.
// If the string is longer than $len, it will be split into a max of $len characters per part.
// returns an array of strings
function split_str($str, $len)
{
    $temp = array();
    $max = strlen($str);
    
    $len = $len ? abs($len) : $max;
    
    if ($len >= $max)
    {
        $temp[] = $str;
        return $temp;
    }
    
    $start = 0;
    $end = $len;
    
    do // what makes things tricky is because strings like arrays start at 0
    {
        while (($end > $start) && !is_punct($str{$end}))
        {
            $end--;
        }
        
        if ($end > $start)
        {
            $end = (($end - $start) < $len) ? $end + 1 : $end;
            $temp[] = substr($str, $start, ($end - $start));
        }
        else
        {
            $end += $len;
            $temp[] = substr($str, $start, $len);
        }      

        $start = $end;
        $end += $len;
    }
    while ($start < $max);
    
    return $temp;
}

// some helper function, returns true if $c is a punctuation, otherwise, false
function is_punct($c)
{
    // change this regex to your liking:
    return preg_match('/^[`~@#%^&*()\-=_+[\]\\{}|;\':",.\/\<\>?\s]$/', $c);
}

// call it like: (just for testing)
$s = 'The quick brown fox jumps over the lazy dog. The lazy dog, jumps over the quick brown fox.';
$t = split_str($s, 10);

// then access each like
$i = 0;
    
foreach ($t as $v)
{
    echo $i++ . ' |' . $v . '|<br />'; // I used | just to see the spaces
}
//var_dump($t);
You can modify the regex to your liking if you want. This function prevents having to copy or create new strings everytime just to get the remaining string and also prevents any recursion. It simply uses the original string the whole time.

This has been tested by me and removed all the possible bugs I can ever find. If you enter a negative length, ex: -10 will be treated as 10. Length of 0 will be treated as the length of the string.

You call it like:
PHP:
$parts = split_str($message, 160);
// then do what you like with the $parts

Sorry for the short variable names, it seems I've been doing too much C++. ^^;

EDIT: @xPlozion: the cutText() was the function you posted ;)
 
Last edited:

diabolo

Community Advocate
Community Support
Messages
1,682
Reaction score
32
Points
48
woah all these different scripts is gonna add to my headache right now;

PHP:
<?php
// cutText Function credit goes to: svihel
// http://us3.php.net/manual/en/function.substr.php#84103

$text = "1000020000300004000050000600007000080000900001000011000120001300014000150001600017000180001900020000210002200023000240002500026000270002800029000300003100032000330003400035000360003700038000390004000041000420004300044000450004600047000480004900050000510005200053000540005500056000570005800059000600006100062000630006400065000660006700068000690007000071000720007300074000750007600077000780007900080000810008200083000840008500086000870008800099000";
$maxlength = "160";

function cutText($string, $setlength) {
    $length = $setlength;
    $strlen = strlen($string);
    if($length<strlen($string)){
        while (($string{$length} != " ") AND ($length > 0)) {
            $length--;
        }
        if ($length == 0) { 
          $math = $strlen - $setlength;
          $total = $strlen/$setlength;
          i = "0";
          while($string > $setlength){
            $message[$i] = substr($string, 0, $setlength);
            $string = substr($string, -$math);
            
            $math = $strlen - ($setlength * $i);
            $i = $i++
          } 
        } else { return substr($string, 0, $length); }
    } else { return $string; }
}


echo cutText($text, $maxlength);
?>

this is what I was working on, but it is way unfinished
 

natsuki

New Member
Messages
112
Reaction score
0
Points
0
sorry my script looks complicated because it tries to save as much resources as possible so you don't need to save temp strings every time, and i've ironed out all the bugs i could find in it so it's reusable >_< (but the code is actually simpler than yours once you understand it lol)

that code your working one is kinda similar to the first one i posted, though your code doesn't seem to do what you want it to..
 
Last edited:

mfurqanabid

New Member
Messages
37
Reaction score
0
Points
0
Code:
<?php
$lengthover = strlen($message);
if($lengthover > 160){
  $messagepart_1 = substr($message, 0, 160);
}  
echo $messagepart_1;
?>
 

xPlozion

New Member
Messages
868
Reaction score
1
Points
0
Code:
<?php
$lengthover = strlen($message);
if($lengthover > 160){
  $messagepart_1 = substr($message, 0, 160);
}  
echo $messagepart_1;
?>
with that script, it will cut the word in half if it lands half way in there. if the 160th character lands on n in donkey, it will only show don, which is not what he wants. there's several answers already on how to do this. each coded differently, but they all serve one general purpose.
 
Top