29 Replies Latest reply: May 2, 2012 6:19 AM by Jonathan Fortis RSS

    truncate text to the end of a word

    Jonathan Fortis Community Member

      i have made a truncate using the code i will shown by bregent, however i want to extend this to make sure the full word is shown rather than cutting off

       

      code here

       

      $query_Recordset1 = "SELECT tk_job_title, tk_job_location, tk_job_salary, LEFT(tk_job_desc, 80) as truncated_job_desc FROM think_jobsearch ORDER BY think_jobsearch.tk_job_title";

      $query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1);

      $Recordset1 = mysql_query($query_limit_Recordset1, $hostprop) or die(mysql_error());

      $row_Recordset1 = mysql_fetch_assoc($Recordset1);

       

       

      and the result of the truncate is

       

      <?php echo $row_Recordset1['truncated_job_desc']; ?>

       

      what do i do to make sre a word is complete?

       

       

      thanks in advance

        • 1. Re: truncate text to the end of a word
          sudarshan.t Community Member

          At the moment, how many letters is it showing by default after you run your truncate function? 80?

           

          If it is showing 80 characters, change the highlited string in the following code. This will display 150 characters.

          $query_Recordset1 = "SELECT tk_job_title, tk_job_location, tk_job_salary, LEFT(tk_job_desc, 150) as truncated_job_desc FROM

           

          • 2. Re: truncate text to the end of a word
            sudarshan.t Community Member

            Also, if you'd like to truncate to the nearest word, you should visit string position - strpos function. You can read about it here:

             

            http://www.ambrosite.com/blog/truncate-long-titles-to-the-nearest-whole-word-using-php-str rpos

            • 3. Re: truncate text to the end of a word
              Jonathan Fortis Community Member

              hi, i know how to chanhe the amount of characters showing i need to know how to show complete words rather than breaking them of half half way throught the word

              • 4. Re: truncate text to the end of a word
                Jonathan Fortis Community Member

                ok so i should change the

                LEFT(tk_job_desc, 150) as truncated_job_desc FROM in the sql statement and use the example you used to truncate the text then specify the length

                 

                echo substr( $title, 0, strrpos( substr( $title, 0, 35), ' ' ) );

                 

                <?php

                 

                echo substr $row_Recordset1['tk_job_desc'], 0 , strrpos( $row_Recordset1['tk_job_desc'], 0, 80), ' ' ) );

                 

                ?>

                 

                would that work?

                • 6. Re: truncate text to the end of a word
                  Jonathan Fortis Community Member

                  so can i change the sql statement from

                   

                  LEFT(tk_job_desc, 150) as truncated_job_desc FROM

                   

                  to

                   

                  job_desc FROM

                  • 7. Re: truncate text to the end of a word
                    sudarshan.t Community Member

                    Yes. Your SQL query will return the entire data available in 'job_desc' and your strrpos statement will truncate it

                    • 8. Re: truncate text to the end of a word
                      Jonathan Fortis Community Member

                      i have tried using <?php echo substr $row_Recordset1['tk_job_desc'], 0 , strrpos( $row_Recordset1['tk_job_desc'], 0, 80), ' ' ) ); ?>

                       

                      and it is showing a sytnax error in dreamweaver

                      • 9. Re: truncate text to the end of a word
                        Jonathan Fortis Community Member

                        i looked again and added two more brackets

                         

                        <?php echo substr ( $row_Recordset1['tk_job_desc'], 0 , strrpos( substr( $row_Recordset1['tk_job_desc'], 0, 80), ' ' ) ); ?>

                         

                        but the results didnt display anything

                        • 10. Re: truncate text to the end of a word
                          sudarshan.t Community Member

                          Hi,

                           

                          Can you post your full PHP + HTML Code here so I can take a look at what might be going wrong and where.

                          • 11. Re: truncate text to the end of a word
                            Jonathan Fortis Community Member

                            the sql statement is currently

                             

                            mysql_select_db($database_hostprop, $hostprop);

                            $query_Recordset1 = "SELECT tk_job_title, tk_job_location, tk_job_salary, LEFT(tk_job_desc, 80) as truncated_job_desc FROM think_jobsearch ORDER BY think_jobsearch.tk_job_title";

                            $query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1);

                            $Recordset1 = mysql_query($query_limit_Recordset1, $hostprop) or die(mysql_error());

                            $row_Recordset1 = mysql_fetch_assoc($Recordset1);

                             

                            the output

                            <?php echo $row_Recordset1['truncated_job_desc']; ?>

                             

                            the changed version is

                             

                            mysql_select_db($database_hostprop, $hostprop);

                            $query_Recordset1 = "SELECT tk_job_title, tk_job_location, tk_job_salary, job_desc FROM think_jobsearch ORDER BY think_jobsearch.tk_job_title";

                            $query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1);

                            $Recordset1 = mysql_query($query_limit_Recordset1, $hostprop) or die(mysql_error());

                            $row_Recordset1 = mysql_fetch_assoc($Recordset1);

                             

                            <?php echo substr ( $row_Recordset1['tk_job_desc'], 0 , strrpos( substr( $row_Recordset1['tk_job_desc'], 0, 80), ' ' ) ); ?>

                             

                             

                            if you need anymore code let me know

                            • 12. Re: truncate text to the end of a word
                              sudarshan.t Community Member

                              Can you upload your site and post a link here?

                              • 13. Re: truncate text to the end of a word
                                Jonathan Fortis Community Member

                                ok here is a link to the page its in the Latest job section (ignore the rest of the formatting)

                                 

                                http://www.thinkfuturerecruitment.co.uk/beta/what-we-do.php

                                • 14. Re: truncate text to the end of a word
                                  sudarshan.t Community Member

                                  Can you define a variable in PHP to call your data from the job_desc table?

                                   

                                  Once you read the data from your desired column, assign it to a variable something like

                                   

                                  $jobdesc = "your-definition-of-the-variable-from-db;

                                  Then, you could use a function to truncate the called text.

                                   

                                  function truncateDesc($input, $numwords, $padding=""){

                                      $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if ($output != $input) $output .= $padding; return $output;

                                  }

                                   

                                  Your next variable would be to truncate the data that is read using the previous function defined above:

                                  $truncated = truncateDesc($jobdesc, 10, "...");

                                   

                                  Then finally, once $truncate variable is defined, you could echo it in your HTML:

                                   

                                  echo "<p>$truncated</p>";

                                   

                                  A static example of this code will be as follows:

                                  <?PHP

                                  $longtext = "This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description. This is some test description.";

                                   

                                  function truncateLong($input, $numwords, $padding="")

                                  { $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if($output != $input) $output .= $padding; return $output; }

                                   

                                  $truncated = truncateLong($longtext, 10, "...");

                                  echo "<p>$truncated</p>";

                                   

                                  ?>

                                  This should ideally work.

                                   

                                  Undo the previous strpos function that you've defined earlier before trying this.

                                  • 15. Re: truncate text to the end of a word
                                    Jonathan Fortis Community Member

                                    >>>>>Can you define a variable in PHP to call your data from the job_desc table?

                                     

                                    the table name isjob_desc

                                     

                                    is that what you mean?

                                     


                                    • 16. Re: truncate text to the end of a word
                                      sudarshan.t Community Member

                                      I meant define a variable that loads the data from job_desc field that is located inside a table in your database.

                                      • 17. Re: truncate text to the end of a word
                                        Jonathan Fortis Community Member

                                        sorry how would i do that then? seems confusing

                                        • 18. Re: truncate text to the end of a word
                                          sudarshan.t Community Member

                                          Something like this:

                                           

                                          Your SQL code:

                                          mysql_select_db($database_testconnection, $testconnection);

                                          $query_Recordset1 = "SELECT job_desc FROM think_jobsearch";

                                          $Recordset1 = mysql_query($query_Recordset1, $testconnection) or die(mysql_error());

                                          $row_Recordset1 = mysql_fetch_assoc($Recordset1);

                                          $totalRows_Recordset1 = mysql_num_rows($Recordset1);

                                          In your main HTML body, if you give this:

                                          <?php echo $row_Recordset1['job_desc']; ?>

                                          You'll get all data in all rows from your table

                                           

                                          Now that we're able to echo the result in the page, we need to truncate it to achieve our objective. For this, look at the code below:

                                          <?PHP

                                          $description = $row_Recordset1['job_desc'];

                                           

                                          function truncateWords($input, $numwords, $padding="")

                                          { $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if($output != $input) $output .= $padding; return $output; }

                                           

                                          $truncated = truncateWords($description, 10, "...");

                                          echo "<p>$truncated</p>";

                                           

                                          ?>

                                          This will cut it to 10 words and add ellipsis (...) to the text beyond 10 words.

                                           

                                          I guess you could figure out to explode the results from your recordset column into different rows and order them as per the Job_ID or something.

                                           

                                          Hope this helps.

                                          • 19. Re: truncate text to the end of a word
                                            Jonathan Fortis Community Member

                                            thanks getting there....i inserted the above code in the top of the php code and amended the correct fields..however its now just showing all the text with no truncating

                                            • 20. Re: truncate text to the end of a word
                                              sudarshan.t Community Member

                                              Post your current code here

                                              • 21. Re: truncate text to the end of a word
                                                Jonathan Fortis Community Member

                                                php

                                                 

                                                <?php require_once('Connections/hostprop.php'); ?>

                                                <?PHP

                                                $description = $row_Recordset1['tk_job_desc'];

                                                 

                                                function truncateWords($input, $numwords, $padding="")

                                                { $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if($output != $input) $output .= $padding; return $output; }

                                                 

                                                $truncated = truncateWords($description, 10, "...");

                                                echo "<p>$truncated</p>";

                                                 

                                                ?>

                                                <?php

                                                if (!function_exists("GetSQLValueString")) {

                                                function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")

                                                {

                                                  if (PHP_VERSION < 6) {

                                                    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

                                                  }

                                                 

                                                 

                                                  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

                                                 

                                                 

                                                  switch ($theType) {

                                                    case "text":

                                                      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

                                                      break;   

                                                    case "long":

                                                    case "int":

                                                      $theValue = ($theValue != "") ? intval($theValue) : "NULL";

                                                      break;

                                                    case "double":

                                                      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";

                                                      break;

                                                    case "date":

                                                      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

                                                      break;

                                                    case "defined":

                                                      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;

                                                      break;

                                                  }

                                                  return $theValue;

                                                }

                                                }

                                                ?>

                                                <?php

                                                // *** Validate request to login to this site.

                                                if (!isset($_SESSION)) {

                                                  session_start();

                                                }

                                                 

                                                 

                                                $loginFormAction = $_SERVER['PHP_SELF'];

                                                if (isset($_GET['accesscheck'])) {

                                                  $_SESSION['PrevUrl'] = $_GET['accesscheck'];

                                                }

                                                 

                                                 

                                                if (isset($_POST['userid'])) {

                                                  $loginUsername=$_POST['userid'];

                                                  $password=$_POST['password'];

                                                  $MM_fldUserAuthorization = "";

                                                  $MM_redirectLoginSuccess = "signup/signup-complete.php";

                                                  $MM_redirectLoginFailed = "failed.php";

                                                  $MM_redirecttoReferrer = false;

                                                  mysql_select_db($database_hostprop, $hostprop);

                                                 

                                                  $LoginRS__query=sprintf("SELECT userid, password FROM think_signup WHERE userid=%s AND password=%s",

                                                    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

                                                  

                                                  $LoginRS = mysql_query($LoginRS__query, $hostprop) or die(mysql_error());

                                                  $loginFoundUser = mysql_num_rows($LoginRS);

                                                  if ($loginFoundUser) {

                                                     $loginStrGroup = "";

                                                   

                                                          if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}

                                                    //declare two session variables and assign them

                                                    $_SESSION['MM_Username'] = $loginUsername;

                                                    $_SESSION['MM_UserGroup'] = $loginStrGroup;               

                                                 

                                                 

                                                    if (isset($_SESSION['PrevUrl']) && false) {

                                                      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];

                                                    }

                                                    header("Location: " . $MM_redirectLoginSuccess );

                                                  }

                                                  else {

                                                    header("Location: ". $MM_redirectLoginFailed );

                                                  }

                                                }

                                                ?>

                                                <?php

                                                if (!function_exists("GetSQLValueString")) {

                                                function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")

                                                {

                                                  if (PHP_VERSION < 6) {

                                                    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

                                                  }

                                                 

                                                 

                                                  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

                                                 

                                                 

                                                  switch ($theType) {

                                                    case "text":

                                                      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

                                                      break;   

                                                    case "long":

                                                    case "int":

                                                      $theValue = ($theValue != "") ? intval($theValue) : "NULL";

                                                      break;

                                                    case "double":

                                                      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";

                                                      break;

                                                    case "date":

                                                      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

                                                      break;

                                                    case "defined":

                                                      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;

                                                      break;

                                                  }

                                                  return $theValue;

                                                }

                                                }

                                                 

                                                 

                                                $maxRows_Recordset1 = 9;

                                                $pageNum_Recordset1 = 0;

                                                if (isset($_GET['pageNum_Recordset1'])) {

                                                  $pageNum_Recordset1 = $_GET['pageNum_Recordset1'];

                                                }

                                                $startRow_Recordset1 = $pageNum_Recordset1 * $maxRows_Recordset1;

                                                 

                                                 

                                                mysql_select_db($database_hostprop, $hostprop);

                                                $query_Recordset1 = "SELECT tk_job_title, tk_job_location, tk_job_salary, tk_job_desc FROM think_jobsearch ORDER BY think_jobsearch.tk_job_title";

                                                $query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1);

                                                $Recordset1 = mysql_query($query_limit_Recordset1, $hostprop) or die(mysql_error());

                                                $row_Recordset1 = mysql_fetch_assoc($Recordset1);

                                                 

                                                 

                                                if (isset($_GET['totalRows_Recordset1'])) {

                                                  $totalRows_Recordset1 = $_GET['totalRows_Recordset1'];

                                                } else {

                                                  $all_Recordset1 = mysql_query($query_Recordset1);

                                                  $totalRows_Recordset1 = mysql_num_rows($all_Recordset1);

                                                }

                                                $pageNum_Recordset1 = 0;

                                                if (isset($_GET['pageNum_Recordset1'])) {

                                                  $pageNum_Recordset1 = $_GET['pageNum_Recordset1'];

                                                }

                                                $startRow_Recordset1 = $pageNum_Recordset1 * $maxRows_Recordset1;

                                                 

                                                 

                                                mysql_select_db($database_hostprop, $hostprop);

                                                $query_Recordset1 = "SELECT tk_job_title, tk_job_location, tk_job_salary, tk_job_desc FROM think_jobsearch ORDER BY tk_job_ID DESC";

                                                $Recordset1 = mysql_query($query_Recordset1, $hostprop) or die(mysql_error());

                                                $row_Recordset1 = mysql_fetch_assoc($Recordset1);

                                                $totalRows_Recordset1 = mysql_num_rows($Recordset1);

                                                 

                                                 

                                                $maxRows_Recordset2 = 3;

                                                $pageNum_Recordset2 = 0;

                                                if (isset($_GET['pageNum_Recordset2'])) {

                                                  $pageNum_Recordset2 = $_GET['pageNum_Recordset2'];

                                                }

                                                $startRow_Recordset2 = $pageNum_Recordset2 * $maxRows_Recordset2;

                                                 

                                                 

                                                mysql_select_db($database_hostprop, $hostprop);

                                                $query_Recordset2 = "SELECT ID, FirstName, Surname, PositionReq, SalaryReq, skills_offered, location, LEFT(CanAdminInfo, 100) as truncated_CanAdminInfo FROM think_signup ORDER BY ID DESC";

                                                $query_limit_Recordset2 = sprintf("%s LIMIT %d, %d", $query_Recordset2, $startRow_Recordset2, $maxRows_Recordset2);

                                                $Recordset2 = mysql_query($query_limit_Recordset2, $hostprop) or die(mysql_error());

                                                $row_Recordset2 = mysql_fetch_assoc($Recordset2);

                                                 

                                                 

                                                if (isset($_GET['totalRows_Recordset2'])) {

                                                  $totalRows_Recordset2 = $_GET['totalRows_Recordset2'];

                                                } else {

                                                  $all_Recordset2 = mysql_query($query_Recordset2);

                                                  $totalRows_Recordset2 = mysql_num_rows($all_Recordset2);

                                                }

                                                $totalPages_Recordset2 = ceil($totalRows_Recordset2/$maxRows_Recordset2)-1;

                                                 

                                                 

                                                mysql_select_db($database_hostprop, $hostprop);

                                                $query_Recordset3 = "SELECT * FROM think_wwd";

                                                $Recordset3 = mysql_query($query_Recordset3, $hostprop) or die(mysql_error());

                                                $row_Recordset3 = mysql_fetch_assoc($Recordset3);

                                                $totalRows_Recordset3 = mysql_num_rows($Recordset3);

                                                ?>

                                                 

                                                 

                                                 

                                                results <?php echo $row_Recordset1['job_desc']; ?>

                                                • 22. Re: truncate text to the end of a word
                                                  sudarshan.t Community Member

                                                  The last line of your code has

                                                   

                                                  results <?php echo $row_Recordset1['job_desc']; ?>

                                                  this is why it's displaying all data. Actually your truncate code is not doing its job.

                                                   

                                                  Try removing the last line and replace it with

                                                  <?PHP

                                                  $description = $row_Recordset1['tk_job_desc'];

                                                  function truncateWords($input, $numwords, $padding="")

                                                  { $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if($output != $input) $output .= $padding; return $output; }

                                                  $truncated = truncateWords($description, 10, "...");

                                                  echo "<p>$truncated</p>";

                                                  ?>

                                                  See if it works

                                                  • 23. Re: truncate text to the end of a word
                                                    Jonathan Fortis Community Member

                                                    this is what i already have in the code which looks the same as above?

                                                     

                                                    <?PHP

                                                    $description = $row_Recordset1['tk_job_desc'];

                                                     

                                                    function truncateWords($input, $numwords, $padding="")

                                                    { $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if($output != $input) $output .= $padding; return $output; }

                                                     

                                                    $truncated = truncateWords($description, 10, "...");

                                                    echo "<p>$truncated</p>";

                                                     

                                                    ?>

                                                    • 24. Re: truncate text to the end of a word
                                                      sudarshan.t Community Member

                                                      I know that. But, I asked you to change where it is placed. And to remove the last line with

                                                      results <?php echo $row_Recordset1['job_desc']; ?>

                                                      • 25. Re: truncate text to the end of a word
                                                        Jonathan Fortis Community Member

                                                        so remove this <?php echo $row_Recordset1['job_desc']; ?>

                                                         

                                                        and replace with this

                                                         

                                                        <?PHP

                                                        $description = $row_Recordset1['tk_job_desc'];

                                                         

                                                        function truncateWords($input, $numwords, $padding="")

                                                        { $output = strtok($input, " \n"); while(--$numwords > 0) $output .= " " . strtok(" \n"); if($output != $input) $output .= $padding; return $output; }

                                                         

                                                        $truncated = truncateWords($description, 10, "...");

                                                        echo "<p>$truncated</p>";

                                                         

                                                        ?>


                                                        • 26. Re: truncate text to the end of a word
                                                          sudarshan.t Community Member

                                                          Yes mate. You should remove that code from the top of your PHP page. It should be present at the bottom.

                                                          • 27. Re: truncate text to the end of a word
                                                            Jonathan Fortis Community Member

                                                            got an error

                                                             

                                                            Fatal error: Cannot redeclare truncatewords() (previously declared in /usr/users1/jonfort/public_html/think/beta/what-we-do.php:5) in /usr/users1/jonfort/public_html/think/beta/what-we-do.php on line 424

                                                             

                                                            that line of code shows

                                                            function truncateWords($input, $numwords, $padding="")

                                                            • 28. Re: truncate text to the end of a word
                                                              sudarshan.t Community Member

                                                              As adviced, you already have the function present between lines 421 an 431. The same function between lines 2 and 11 are redundant. Remove these lines 2 till 11 and it should ideally work.

                                                               

                                                              Cheers,

                                                              ST

                                                              • 29. Re: truncate text to the end of a word
                                                                Jonathan Fortis Community Member

                                                                ok thanks i will try this out and let you know how i get on thanks