Jump to content

not cutting words


masgas

Recommended Posts

hi people!

I have this function which prints an X numbers of characters, but I can't manage to make it not cut words in half... this is the last I tried and it prints the $maxlength=880 but the rest it doesn't print them... what am I doing wrong???

function substring($string, $start, $maxlength){
$strlength = strlen($string);

$trows = ceil($strlength / $maxlength);
for($i=0; $i<$trows; $i++){
$line = substr($string, $start, $maxlength);
$lineB = substr($line, $start, strrpos($line, ' '));
}
return $lineB;

}

thanks for your time!
Link to comment
Share on other sites

This function may help.

function myfragment($s,$n) {
$scan=0;
  while($scan==0){
  if(substr($s,$n,1)==' ' || strlen($s)<$n){
      $scan=1;
  }else{
      $n++;
  }   
  }
  return substr($s,0,$n) . "...";
}

$string="some really really long string";
echo myfragment($string,10);
//This will out put "some really..." - adds 3 dots after the end of the first word after so many characters
Link to comment
Share on other sites

Try this based on my previous function

  function myfragment($s,$n) {
    $scan=0;
    while($scan==0){
      if(substr($s,$n,1)==' ' || strlen($s)<$n){
          $scan=1;
      }else{
          $n++;
      } 
    }
      $fragment=substr($s,0,$n);
      $leftover=trim(substr($s,$n));
      $toreturn=Array($fragment,$leftover);
    return $roretrun;
  }

while(strlen($string)>0){
  $parts=myfragment($string,880);
  echo $parts[0] ."<br>";
  $string=$parts[1];
}


Now I did not test that, but that should print lines that end after the first wrd past 880 characters - then returns the remainder and you can take the 880 again. Trim is there to make sure the next line does not start with a space.

Hope this helps
Link to comment
Share on other sites

I posted this in your other thread by accident but here is the fix

[code]<?php
/*********** Start function *********************/
function substring($string, $maxlength, $page){
$strlength = strlen($string);
// divide the length by the limit
$trows = ceil($strlength / $maxlength) +1;
$start = 0;
$data = array();
for($i=1; $i<=$trows; $i++){
// echo "Old Start: $start<br>";
$line = substr($string, $start, $maxlength);
$pos = strrpos($line, ' ');
$data[$i] = substr($string, $start, $pos);
$string = substr($string, $pos);
}
return $data[$page];
}
/************** End Function ******************/

$maxlength = 25;  // set this for your max length
if (!isset($_GET['page'])){
  $page = 1;
  } else {
  $page = $_GET['page'];
  }
echo "<table width='300' height='455' border=1>" ;
mysql_connect("$host", "$username", "$password")or die("no conn DB");
mysql_select_db("$db_name")or die("no DB");
$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 1";
$result=mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
    $string = $row["text1"];
    echo "<tr><td>".substring($string, $maxlength, $page)."</td></tr>";
}
echo "</table>";
?>

<?php
$stringlength = strlen($string);
echo "<p align=center>";

// Sets link for previous 25 and return to page 1
    if($page != 1){
        $pageprev = ($page - 1);
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=1\"><<</a>&nbsp;&nbsp;";
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$pageprev\">PREV</a>&nbsp;&nbsp;&nbsp;";
    }else{
        echo "PREV&nbsp;&nbsp;&nbsp;";
    }
// Find out the total number of pages depending on the limit set
$numofpages = ($stringlength / $maxlength)+1;
$totalpages = round($numofpages);
// Loop thru all the pages and echo out the links
    for($i = 1; $i <= $numofpages; $i++){
        if($i == $page){
            echo $i." ";
        }else{
            echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\">$i</a> ";
        }
    }
// Check for straglers after the limit blocks
    if(($stringlength % $maxlength) != 0){
        if($i == $page){
            echo $i." ";
        }else{
            echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\">$i</a> ";
        }
    }
// Print out the Next 25 and Goto Last page links
    if(($stringlength - ($maxlength * $page)) > 0){
        $pagenext = $page+1;
          echo "&nbsp;&nbsp;&nbsp;<a href=\"".$_SERVER['PHP_SELF']."?page=$pagenext\">NEXT</a>&nbsp;&nbsp;&nbsp;";
          echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$totalpages\">>></a>&nbsp;&nbsp;";
    }else{
        echo("&nbsp;&nbsp;&nbsp;NEXT");
    }
echo "</p>";
mysql_close();
?>[/code]

This might give you a blank page at the end because of the +1 when you divide the length by maxlength. Reason being is it is no longer a constant. You want to keep the length below $maxlength but when you look for whole words you bring the pointer back X number of charachtors. So I added 1 more page to make sure you get everything. I will repost with a fix in a little bit.

Ray
Link to comment
Share on other sites

OK here is the revised, and hopefully final version of this function. Basically the function takes a blog or text area and breaks it up into segment specified by the $maxlength variables. Then it shortens that by finding the closest space so you do not break up words. Then it repositions itself with a new string length and loops till the strlength reaches zero. then pages the results
One of the problem I had with this is trying to loop through the string the least amount of time. the loop cannot be the stringlength / maxlength because it changes depending on where spaces end up. So if you have a string of 120 characters and you want to make the cut off 60 characters the loop will not be 2 because if a word is right in the middle of the 60th character you know have the secong part of the string longer than 60.

Well here it is. If anyone can help making the code a little cleaner That would be cool.
[code]<?php
/*********** Start function *********************/
function substring($string, $maxlength, $page){
$strlength = strlen($string);
$trows = ceil($strlength / $maxlength);
$start = 0;
$data = array();
$i = 1;
  while($strlength > 0){
  $line = substr($string, $start, $maxlength);
    if($strlength <= $maxlength){
    $data[$i] = $string;
    $strlength = 0;
    } else {
    $pos = strrpos($line, ' ');
    $data[$i] = substr($string, $start, $pos);
    $string = substr($string, $pos);
    $strlength = strlen($string);
    }
  $i++;
  }
  $count = count($data);
  $return = addslashes($data[$page]);
return array($count, "$return");
}
/************** End Function ******************/

$tbl_name = "htmlpage";
$maxlength = 60;
if (!isset($_GET['page'])){
  $page = 1;
  } else {
  $page = $_GET['page'];
  }
echo "<table width='300' height='455' border=1>" ;
// connect to database
mysql_connect("$host", "$username", "$password")or die("no conn DB");
mysql_select_db("$db_name")or die("no DB");
$sql="SELECT * FROM $tbl_name ORDER BY id DESC LIMIT 1";
$result=mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$string = $row["text1"];
$data = substring($string, $maxlength, $page);
echo "<tr>
      <td>".$data[1]."</td>
      </tr>
      </table>";

$stringlength = strlen($string);
echo "<p align=center>";

// Sets link for previous and return to page 1
    if($page != 1){
        $pageprev = ($page - 1);
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=1\"><<</a>&nbsp;&nbsp;";
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$pageprev\">PREV</a>&nbsp;&nbsp;&nbsp;";
    }else{
        echo "PREV&nbsp;&nbsp;&nbsp;";
    }
// Find out the total number of pages depending on the limit set
$numofpages = $data[0];
// Loop thru all the pages and echo out the links
    for($i = 1; $i <= $numofpages; $i++){
        if($i == $page){
            echo $i." ";
        }else{
            echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\">$i</a> ";
        }
    }
// Print out the Next and Goto Last page links
    if($page < $data[0]){
        $pagenext = $page++;
          echo "&nbsp;&nbsp;&nbsp;<a href=\"".$_SERVER['PHP_SELF']."?page=$pagenext\">NEXT</a>&nbsp;&nbsp;&nbsp;";
          echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$numofpages\">>></a>&nbsp;&nbsp;";
    }else{
        echo("&nbsp;&nbsp;&nbsp;NEXT");
    }
echo "</p>";
mysql_close();
?>[/code]

Ray
Link to comment
Share on other sites

enjoy... that'll limit how many words in the string, if over the max, i'll cut after the last word and add '...'
[code]<?
function filter_wordlimit($string, $length=50, $ellipsis='...'){
return count($words = preg_split('/\s+/', ltrim($string), $length + 1)) > $length ? rtrim(substr($string, 0, strlen($string) - strlen(end($words)))) . $ellipsis : $string;
}
?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.